Last active
November 14, 2018 14:20
-
-
Save Wesitos/bf9ff4f233eb3ae6b727 to your computer and use it in GitHub Desktop.
Graphql-core Tornado Middleware
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
| from tornado.concurrent import Future | |
| from tornado.ioloop import IOLoop | |
| from asyncio import iscoroutine | |
| from tornado import gen | |
| from graphql.core.pyutils.defer import Deferred | |
| def process_future_result(deferred): | |
| def handle_future_result(future): | |
| exception = future.exception() | |
| if exception: | |
| deferred.errback(exception) | |
| else: | |
| deferred.callback(future.result()) | |
| return handle_future_result | |
| class TornadoExecutionMiddleware(object): | |
| @staticmethod | |
| def run_resolve_fn(resolver, original_resolver): | |
| result = resolver() | |
| if isinstance(result, Future) or iscoroutine(result): | |
| future = gen.convert_yielded(result) | |
| d = Deferred() | |
| IOLoop.current().add_future(future, process_future_result(d)) | |
| return d | |
| # Si no es future ni corutina | |
| return result | |
| @staticmethod | |
| def execution_result(executor): | |
| future = Future() | |
| result = executor() | |
| assert isinstance(result, Deferred), 'Another middleware has converted the execution result ' \ | |
| 'away from a Deferred.' | |
| result.add_callbacks(future.set_result, future.set_exception) | |
| return future |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Deferred has been removed from graphql-core, here is an updated version:
https://gist.github.com/isi-gach/daef0b34ec5af6f026af52d593131c64