在Ariadne 介绍文档中,完整的代码不包括 http 服务器部分。该页面指示您启动外部服务器,将服务器指向您的代码。
该文档有一个wsgi page,它再次不包括服务器部分。
python 本身应该已经附带了一个内置的 WSGI 服务器。有没有包含服务器部分的简单示例?我假设应该对上述介绍示例进行简单扩展。
在Ariadne 介绍文档中,完整的代码不包括 http 服务器部分。该页面指示您启动外部服务器,将服务器指向您的代码。
该文档有一个wsgi page,它再次不包括服务器部分。
python 本身应该已经附带了一个内置的 WSGI 服务器。有没有包含服务器部分的简单示例?我假设应该对上述介绍示例进行简单扩展。
以下示例有效:
#!/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
Playground 还发送自省查询。这些查询每秒左右更新一次。该模式用于验证用户在面板中键入的查询。
与 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)