1+ from flask import Flask , make_response
2+ from flask_sockets import Sockets
3+ from graphql_ws .server import GeventSubscriptionServer
4+ import json
5+ from template import render_graphiql
6+ import graphene
7+ import gevent
8+ from flask_graphql import GraphQLView
9+ import asyncio
10+ from rx import Observable
11+
12+
13+ class Query (graphene .ObjectType ):
14+ base = graphene .String ()
15+
16+
17+ class Subscription (graphene .ObjectType ):
18+
19+ username = graphene .String ()
20+
21+
22+ def resolve_username (root , info ):
23+ return Observable .interval (1000 ).map (lambda i : "{0}" .format (i ))
24+
25+
26+ schema = graphene .Schema (query = Query , subscription = Subscription )
27+
28+
29+
30+ app = Flask (__name__ )
31+ app .debug = True
32+ sockets = Sockets (app )
33+
34+
35+ @app .route ('/graphiql' )
36+ def graphql_view ():
37+ return make_response (render_graphiql ())
38+
39+ app .add_url_rule (
40+ '/graphql' , view_func = GraphQLView .as_view ('graphql' , schema = schema , graphiql = False ))
41+
42+ subscription_server = GeventSubscriptionServer (schema )
43+ app .app_protocol = lambda environ_path_info : 'graphql-ws'
44+
45+ @sockets .route ('/subscriptions' )
46+ def echo_socket (ws ):
47+ subscription_server .handle (ws )
48+ return []
49+
50+
51+ if __name__ == "__main__" :
52+ from gevent import pywsgi
53+ from geventwebsocket .handler import WebSocketHandler
54+ server = pywsgi .WSGIServer (('' , 5000 ), app , handler_class = WebSocketHandler )
55+ server .serve_forever ()
0 commit comments