没有外部服务器的 Python GraphQL Ariadne WSGI 示例

Posted

技术标签:

【中文标题】没有外部服务器的 Python GraphQL Ariadne WSGI 示例【英文标题】:Python GraphQL Ariadne WSGI Example Without External Server 【发布时间】:2020-06-19 10:03:03 【问题描述】:

Ariadne intro doc 中的完整代码不包括 http 服务器部分。该页面指示您启动外部服务器,将服务器指向您的代码。

该文档有一个wsgi page,它同样不包括服务器部分。

python 本身应该已经内置了 WSGI 服务器。有没有包含服务器部分的简单示例?我假设应该对上述介绍示例进行简单扩展。

【问题讨论】:

【参考方案1】:

以下示例工作:

#!/usr/bin/env python

from ariadne import gql, QueryType, make_executable_schema
from ariadne.wsgi import GraphQL

type_defs = gql("""
    type Query 
        hello: String!
    
""")

query = QueryType()

@query.field("hello")
def resolve_hello(_, info):
    ##request = info.context["request"]
    ##user_agent = request.headers.get("user-agent", "guest")
    user_agent = info.context["HTTP_USER_AGENT"]
    return "Hello, %s!..." % user_agent #

schema = make_executable_schema(type_defs, query)
application = GraphQL(schema, debug=True)

if __name__ == '__main__':
    do_single = False
    from wsgiref.simple_server import make_server
    httpd = make_server('localhost', 8051, application)
    if do_single:
        # Wait for a single request, serve it and quit.
        httpd.handle_request()
    else:
        httpd.serve_forever(.5)

基本上,它与 Ariadne 介绍示例提供的代码相同,但有两处更改。一方面,它修复了没有请求成员的 info.context。第二个是将应用程序传递给 wsgiref.simple_server.make_server() 调用。

一旦此示例服务器运行,Ariadne 内置 Playground 将在浏览器中显示您可以发送的实际请求。它显示了两种发送查询的方式:

从操场面板发帖:

        query  hello 

或者游乐场按钮提示显示通过 curl 发送的相同请求:

        curl 'http://localhost:8051/graphql' \
           -H 'Accept-Encoding: gzip, deflate, br' \
           -H 'Content-Type: application/json' \
           -H 'Accept: application/json' -H 'Connection: keep-alive' \
           -H 'DNT: 1' -H 'Origin: http://localhost:8051' \
           --data-binary '"query":"hello"' --compressed

游乐场还发送自省查询。这些查询每秒左右更新一次。该模式用于验证用户在面板中键入的查询。

与 Ariadne 无关的客户端可用于从 python 发送相同的请求:

#!/usr/bin/env python
#    https://github.com/prisma-labs/python-graphql-client

from graphqlclient import GraphQLClient

client = GraphQLClient('http://127.0.0.1:8051/')

result = client.execute('''

  hello

''')

print(result)

【讨论】:

以上是关于没有外部服务器的 Python GraphQL Ariadne WSGI 示例的主要内容,如果未能解决你的问题,请参考以下文章

如何使用模拟的 graphql API 和外部服务的 GraphQL 端点

有没有办法将 Java 服务器中的 GraphQL 查询转换为 SPARQL 查询?

AWS 放大和 graphql - 外部数据库

外部 WebSocket 服务器上的 Apollo-Server GraphQL 订阅

详解Python Graphql

寻找服务器端 GraphQL 订阅监听器的代码