|
1 | 1 | """Construction of routes for web app and API"""
|
| 2 | +import asyncio |
2 | 3 | import os
|
3 | 4 |
|
4 |
| -from ariadne import graphql_sync |
| 5 | +from ariadne import graphql, graphql_sync |
5 | 6 | from ariadne.constants import PLAYGROUND_HTML
|
6 | 7 | from flask import Blueprint, current_app, jsonify, request
|
7 | 8 | from flask_cors import cross_origin
|
8 | 9 |
|
9 | 10 | from .auth import request_jwt, requires_auth
|
10 | 11 | from .exceptions import AuthenticationFailed, format_database_errors
|
11 | 12 | from .graph_ql.schema import full_api_schema, query_api_schema
|
| 13 | +from .loaders import ProductLoader, SizeLoader, TagsForBoxLoader |
12 | 14 |
|
13 | 15 | # Blueprint for query-only API. Deployed on the 'api*' subdomains
|
14 | 16 | api_bp = Blueprint("api_bp", __name__)
|
@@ -82,15 +84,27 @@ def graphql_playgroud():
|
82 | 84 | @cross_origin(origin="localhost", headers=["Content-Type", "Authorization"])
|
83 | 85 | @requires_auth
|
84 | 86 | def graphql_server():
|
85 |
| - # Note: Passing the request to the context is optional. |
86 |
| - # In Flask, the current request is always accessible as flask.request |
87 |
| - success, result = graphql_sync( |
88 |
| - full_api_schema, |
89 |
| - data=request.get_json(), |
90 |
| - context_value=request, |
91 |
| - debug=current_app.debug, |
92 |
| - introspection=current_app.debug, |
93 |
| - error_formatter=format_database_errors, |
| 87 | + # Start async event loop, required for DataLoader construction, cf. |
| 88 | + # https://github.com/graphql-python/graphql-core/issues/71#issuecomment-620106364 |
| 89 | + loop = asyncio.new_event_loop() |
| 90 | + asyncio.set_event_loop(loop) |
| 91 | + |
| 92 | + # Create DataLoaders and persist them for the time of processing the request |
| 93 | + context = { |
| 94 | + "product_loader": ProductLoader(), |
| 95 | + "size_loader": SizeLoader(), |
| 96 | + "tags_for_box_loader": TagsForBoxLoader(), |
| 97 | + } |
| 98 | + |
| 99 | + success, result = loop.run_until_complete( |
| 100 | + graphql( |
| 101 | + full_api_schema, |
| 102 | + data=request.get_json(), |
| 103 | + context_value=context, |
| 104 | + debug=current_app.debug, |
| 105 | + introspection=current_app.debug, |
| 106 | + error_formatter=format_database_errors, |
| 107 | + ) |
94 | 108 | )
|
95 | 109 |
|
96 | 110 | status_code = 200 if success else 400
|
|
0 commit comments