def create_app(): app = Flask(__name__) @app.route('/') def index(): return redirect('/graphql') # GraphQL endpoints ---------------------------------------------- app.add_url_rule('/graphql', view_func=(GraphQLView.as_view('graphql', schema=schema, graphiql=True))) # Optional, for adding batch query support (used in Apollo-Client) app.add_url_rule('/graphql/batch', view_func=(GraphQLView.as_view('graphql-batch', schema=schema, batch=True))) # RESTful methods for authentication ----------------------------- # TODO: provide this via GraphQL API # @app.errorhandler(401) # def handle_401(error): # return Response(str(error), 401, { # 'WWWAuthenticate': 'Basic realm="Login Required"', # }) # @app.route('/auth', methods=['POST']) # def authenticate_user(): # username = request.form['username'] # password = request.form['password'] # user = verify_credentials(username, password) # if user: # token = _create_user_jwt(user) # return json.dumps({'token': token.decode()}), 200, { # 'Content-type': 'text/json'} # raise Unauthorized('Bad username / password') # Websockets ----------------------------------------------------- sockets = Sockets(app) app.app_protocol = lambda environ_path_info: 'graphql-ws' subscription_server = GeventSubscriptionServer(schema) @sockets.route('/graphql') def echo_socket(ws): subscription_server.handle(ws) return [] # Add CORS support ----------------------------------------------- CORS(app) return app
def setup_subscription_server(app): from voyage.schema import schema sockets = Sockets(app) subscription_server = GeventSubscriptionServer(schema) app.app_protocol = lambda environ_path_info: 'graphql-ws' @sockets.route('/subscriptions') def echo_socket(ws): subscription_server.handle(ws) return []
def test_subscription_server_smoke(): GeventSubscriptionServer(schema=None)
schema = Schema(query=Query, mutation=Mutation, subscription=Subscription) view_func = OverriddenView.as_view("graphql", schema=schema, backend=CustomBackend(), graphiql=True) app = Flask(__name__) app.logger = logger app.add_url_rule("/", view_func=view_func) # CORS(app) sockets = Sockets(app) subscription_server = GeventSubscriptionServer(schema) app.app_protocol = lambda environ_path_info: 'graphql-ws' CORS(app) @sockets.route('/subscriptions') def echo_socket(ws): subscription_server.handle(ws) return [] @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
def _server_test_start(self, background=False): """ kosmos 'j.servers.graphql._server_test_start()' :param manual means the server is run manually using e.g. kosmos 'j.servers.rack.start(background=True)' """ if not background: self.install() rack = j.servers.rack.get() from bottle import request, Bottle, abort, static_file, template from .GraphqlBottle import graphql_middleware from geventwebsocket import WebSocketError from .schema import schema from graphql_ws.gevent import GeventSubscriptionServer app = Bottle() # expose graphql end point graphql_middleware(app, "/graphql", schema) # expose graphiql @app.route("/graphiql") def graphiql(): return static_file("graphiql.html", root="%s/html" % self._dirpath) # simple test, making sure websocket protocol is running @app.route("/websocket") def websockets(): return template( """ <!DOCTYPE html> <html> <head> <script type="text/javascript"> var ws = new WebSocket("ws://{{ip}}:7778/websockets"); ws.onopen = function() { ws.send("Hello, world"); }; ws.onmessage = function (evt) { alert(evt.data); }; </script> </head> </html> """, ip=self.ip, ) # expose posts example # add post from simple for to save in bcdb @app.route("/posts", method="GET") @app.route("/posts", method="POST") def posts(): model_objects = None if request.method == "POST": data = self.parse_data(request.body) # Create a model with the data and save the model for later retrieval model = j.application.bcdb_system.model_get( schema=self._SCHEMA_TEXT) model_objects = model.new() model_objects.info_id = data["id"] model_objects.title = data["title"] model_objects.name = data["name"] model_objects.author = data["author"] model_objects.save() with open(self._dirpath + "/html/posts.html") as s: return s.read().replace("{ip_address}", self.ip) # test graphql subscriptions @app.route("/counter") def counter(): with open(self._dirpath + "/html/counter.html") as s: return s.read().replace("{ip_address}", self.ip) # websockets app websockets_app = Bottle() subscription_server = GeventSubscriptionServer(schema) websockets_app.app_protocol = lambda environ_path_info: "graphql-ws" @websockets_app.route("/subscriptions") def echo_socket(): wsock = request.environ.get("wsgi.websocket") if not wsock: abort(400, "Expected WebSocket request.") subscription_server.handle(wsock) return [] @websockets_app.route("/websockets") def handle_websocket(): wsock = request.environ.get("wsgi.websocket") if not wsock: abort(400, "Expected WebSocket request.") while True: try: message = wsock.receive() wsock.send("Your message was: %r" % message) except WebSocketError: break # svelete apollo graphql APP # -- START -- # @app.route("/svelte") def svelte(): return static_file("index.html", root="%s/html/svelte-apollo/public" % self._dirpath) @app.route("/<name>") def serve_static(name): if name in [ "global.css", "bundle.css", "bundle.js", "bundle.js.map", "bundle.css.map", "favicon.png" ]: return static_file(name, root="%s/html/svelte-apollo/public" % self._dirpath) abort(404) # -- END -- # # add a bottle webserver to it rack.bottle_server_add(name="graphql", port=7777, app=app) rack.bottle_server_add(name="graphql_subscriptions", port=7778, app=websockets_app, websocket=True) rack.start() else: S = """ . /sandbox/env.sh; kosmos 'j.servers.graphql._server_test_start()' """ j.servers.tmux.execute(S)