Last active
November 25, 2019 21:52
-
-
Save agritheory/b3b46eead92133848bcb5bd73f728d57 to your computer and use it in GitHub Desktop.
Quart/ Ariadne example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
# graphql query to run in the playground | |
{ | |
hello | |
} | |
""" | |
from ariadne import QueryType, graphql, make_executable_schema | |
from ariadne.constants import PLAYGROUND_HTML | |
from quart import Quart, request, jsonify | |
from ariadne.asgi import GraphQL | |
app = Quart(__name__) | |
# define a graphql schema | |
type_defs = """ | |
type Query { | |
hello: String! | |
} | |
""" | |
query = QueryType() # graphql backend seems to require a query object, everybody uses this pattern | |
# resolver for the field 'hello' | |
@query.field("hello") | |
async def resolve_hello(_, info) -> str: | |
request = info.context | |
user_agent = request.headers.get("User-Agent", "Guest") | |
return "Hello, %s!" % user_agent | |
schema = make_executable_schema(type_defs, query) # kind of magical | |
@app.route("/", methods=["GET"]) | |
async def index() -> str: # just here to confirm quart is running | |
return "Hello, Ariadne" | |
@app.route("/graphql", methods=["GET"]) | |
async def graphql_playgroud() -> str: # supplies playground environment | |
return PLAYGROUND_HTML, 200 | |
@app.route("/graphql", methods=["POST"]) | |
async def graphql_server() -> str: | |
data = await request.get_json() | |
success, result = await graphql( # this is the async interface, flask uses sync_graphql | |
schema, | |
data, | |
context_value=request, | |
debug=app.debug | |
) | |
return jsonify(result), 200 if success else 400 | |
if __name__ == "__main__": | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment