0

In the Ariadne intro doc the complete code does not include a http server part. The page instruct you to fire an external server, point the server to your code.

The doc has a wsgi page, which again does not include a server part.

The python itself should have already shipped with a built-in WSGI server. Is there any simple example that include the server part? I assume a simple extension to the above intro example should do.

minghua
  • 5,981
  • 6
  • 45
  • 71

1 Answers1

0

The following sample works:

#!/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)

Basically it is the same code provided by the Ariadne intro sample with two changes. For one, it fixed info.context which does not have a request member. And the second is to pass the application to a wsgiref.simple_server.make_server() call.

Once this sample server is running, the Ariadne built-in playground will show in browser the actual request that you can send. It shows two ways of sending a query:

Post from the playground panel:

        query { hello }

Or a playground button tip shows the same request sent through 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

The playground also sends introspection queries. Those queries are updated every second or so. The schema is used to validate the query typed by the user into the panel.

A client, which is not tied to Ariadne can be used to send the same request from 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)
minghua
  • 5,981
  • 6
  • 45
  • 71