예제 #1
0
def create(schema):

    app = Sanic()

    @app.middleware('request')
    async def setup_e2e(request):
        await datasub.monitoring.e2e.enter(request)

    @app.middleware('response')
    async def teardown_e2e(request, response):
        await datasub.monitoring.e2e.leave(request, response)

    subscription_server = WsLibSubscriptionServer(schema)

    @app.websocket('/subscriptions', subprotocols=['graphql-ws'])
    async def subscriptions(request, ws):
        await subscription_server.handle(ws)
        return ws

    app.add_route(GraphQLView.as_view(schema=schema, graphiql=True),
                  '/graphql')

    app.add_route(GraphQLView.as_view(schema=schema, batch=True),
                  '/graphql/batch')

    app.add_route(GraphQLView.as_view(schema=monitoring_schema, graphiql=True),
                  '/monitoring/graphql')

    app.add_route(GraphQLView.as_view(schema=monitoring_schema, batch=True),
                  '/monitoring/graphql/batch')

    return app
예제 #2
0
def init_graphql(app, loop):
    app.add_route(
        GraphQLView.as_view(schema=binance_1m_schema,
                            batch=True,
                            graphiql=True),
        '/candles',
    )
예제 #3
0
def create_app(path="/graphql", **kwargs):
    app = Sanic(__name__)
    app.debug = True

    schema = kwargs.pop("schema", None) or Schema
    async_executor = kwargs.pop("async_executor", False)

    if async_executor:

        @app.listener("before_server_start")
        def init_async_executor(app, loop):
            executor = AsyncioExecutor(loop)
            app.add_route(
                GraphQLView.as_view(schema=schema, executor=executor,
                                    **kwargs), path)

        @app.listener("before_server_stop")
        def remove_graphql_endpoint(app, loop):
            app.remove_route(path)

    else:
        app.add_route(GraphQLView.as_view(schema=schema, **kwargs), path)

    app.client = SanicTestClient(app)
    return app
예제 #4
0
def create_graphql_app(root_object: PentContextfulObject,
                       schema: GraphQLSchema,
                       debug: bool = True) -> Sanic:
    """ Creates a Sanic app and adds a graphql/graphiql endpoint """
    app = Sanic(__name__)
    app.debug = debug

    if debug:
        # hack from https://github.com/channelcat/sanic/issues/168
        # for some reason pylint is confused by this import
        #E0611 no name in module
        #pylint: disable=E0611
        from aoiklivereload import LiveReloader
        reloader = LiveReloader()
        reloader.start_watcher_thread()

    # this is totally gross and I need a better story for managing context lifetime
    # versus loader lifetime. The context houses the in-memory shards in in memory
    # case currently so you cannot create a new one with every request. However
    # you do need a new loader every request because it is affined with its
    # asyncio event loop
    def root_factory() -> Any:
        root_object.context.loader = PentLoader(root_object.context)
        return root_object

    app.add_route(
        GraphQLView.as_view(schema=schema,
                            graphiql=True,
                            root_factory=root_factory,
                            context=root_object.context), '/graphql')
    return app
예제 #5
0
def create_app(path="/graphql", **kwargs):
    app = Sanic(__name__)
    app.debug = True

    schema = kwargs.pop("schema", None) or Schema
    app.add_route(GraphQLView.as_view(schema=schema, **kwargs), path)

    app.client = SanicTestClient(app)
    return app
예제 #6
0
 def init_web_route(app, loop):
     print("初始化web路由")
     app.add_route(
         GraphQLView.as_view(schema=schema,
                             context=dict({"session": DBSession()},
                                          **get_dataloaders()),
                             graphiql_template=TEMPLATE,
                             **kwargs),
         "/web",
     )
예제 #7
0
 def init_async_executor(app, loop):
     executor = AsyncioExecutor(loop)
     app.add_route(
         GraphQLView.as_view(schema=schema,
                             executor=executor,
                             context=dict({"session": DBSession()},
                                          **get_dataloaders()),
                             **kwargs),
         path,
     )
예제 #8
0
 async def init_graphql(app, loop):
     # Disable graphql route if testing
     if config_name != 'test':
         from .http.graphql import schema
         from graphql.execution.executors.asyncio import AsyncioExecutor
         app.add_route(
             GraphQLView.as_view(
                 schema=schema,
                 executor=AsyncioExecutor(loop=loop),
                 graphiql=True,
             ), '/graphql')
예제 #9
0
def init_graphql(app, loop):

    schema.event_loop = loop
    subscription_server.loop = loop

    # app.add_route(
    #      GraphQLView.as_view(schema=schema, graphiql=True, allow_subscriptions=True),
    #      '/graphiql', methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])

    app.add_route(GraphQLView.as_view(schema=schema,
                                      graphiql=True,
                                      executor=AsyncioExecutor(loop=loop)),
                  '/graphql',
                  methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
예제 #10
0
def init_graphql(app, loop):
    print(os.getcwd())
    for root, dirs, files in os.walk('pocportal/apps'):
        for file in files:
            print(file)
            if file != 'graphql.py':
                continue
            package = root.replace('/', '.')
            import_module('%s.graphql' % package)

    basequerychildren = tuple(BaseQuery.__subclasses__())
    MainQuery = type('MainQuery', tuple(basequerychildren), {})
    schema = graphene.Schema(query=MainQuery)

    executor = AsyncioExecutor(loop)

    app.add_route(
        GraphQLView.as_view(schema=schema, graphiql=True, executor=executor),
        '/graphql')
예제 #11
0
파일: app.py 프로젝트: plasx/sanicgql
from sanic_graphql import GraphQLView
from sanic import Sanic
from schema import schema

app = Sanic(__name__)
app.debug = True

app.add_route(GraphQLView.as_view(schema=schema, graphiql=True), '/graphql')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
예제 #12
0
from sanic import Blueprint
from sanic_graphql import GraphQLView
# from server.resolvers import schema_test
# from server.resolvers.user.user import user_schema

from server.apis.grapql.resolvers.user import user_schema

bp = Blueprint('graph', url_prefix='/graph')

bp.add_route(GraphQLView.as_view(schema=user_schema, graphiql=True),
             '/graphql/user')
bp.add_route(GraphQLView.as_view(schema=user_schema, batch=True),
             '/graphql/user/batch')
예제 #13
0
    cmt1 = Comment(id=1, author=dainese, text="Awesome!")
    comments.update(dict((c.id, c) for c in [cmt0, cmt1]))

    post0 = Post(
        id=0, author=chester,
        text="Hello world")
    post1 = Post(
        id=1, author=chester,
        text="It's Graphs All the way Down!",
        comments=[cmt0, cmt1])
    posts.update(dict((p.id, p) for p in [post0, post1]))


if __name__ == "__main__":
    asyncio.set_event_loop(uvloop.new_event_loop())
    loop = asyncio.get_event_loop()

    graphql_view = GraphQLView.as_view(
        schema=Schema(query=MyRootQuery, mutation=MyRootMutation),
        executor=AsyncioExecutor(loop=loop))
    app.add_route(graphql_view, "/graphql", methods=["POST"])

    server = app.create_server(host="0.0.0.0", port=9487, debug=True)
    task = asyncio.ensure_future(server)
    signal(SIGINT, lambda s, f: loop.stop())

    try:
        loop.run_forever()
    except Exception:
        loop.stop()
예제 #14
0
def init_graphql(app, loop):
    app.add_route(
        GraphQLView.as_view(schema=schema,
                            executor=AsyncioExecutor(loop=loop)), '/graphql')
예제 #15
0
from sanic_graphql import GraphQLView

from sanic import Sanic
from sanic_cors import CORS

app = Sanic("ml_dash.server")
# CORS(app)
CORS(app, resources={r"/*": {"origins": "*"}}, automatic_options=True)

# NOTE: disable for laziness. Should enable it in the future.
# @app.listener('before_server_start')
# def init_graphql(app, loop):
#     app.add_route(GraphQLView.as_view(schema=schema, executor=AsyncioExecutor(loop=loop)), '/graphql')

# new graphQL endpoints
app.add_route(GraphQLView.as_view(schema=schema, graphiql=True),
              '/graphql',
              methods=['GET', 'POST', 'FETCH', 'OPTIONS'])
app.add_route(GraphQLView.as_view(schema=schema, batch=True),
              '/graphql/batch',
              methods=['GET', 'POST', 'FETCH', 'OPTIONS'])


@app.listener('before_server_start')
def setup_static(app, loop):
    from ml_dash import config
    from os.path import expanduser
    app.static('/files',
               expanduser(config.Args.logdir),
               use_modified_since=True,
               use_content_range=True,
예제 #16
0
def init_graphql(app, loop):
    app.add_route(
        GraphQLView.as_view(schema=gql.schema,
                            graphiql=True,
                            enable_async=True,
                            executor=AsyncioExecutor(loop=loop)), '/graphql')
예제 #17
0
파일: app.py 프로젝트: grazor/sanic-graphql
 def init_async_executor(app, loop):
     executor = AsyncioExecutor(loop)
     app.add_route(
         GraphQLView.as_view(schema=schema, executor=executor,
                             **kwargs), path)
예제 #18
0
from sanic_graphql import GraphQLView

from .app import create_app, url_string, parametrize_sync_async_app_test
from .schema import Schema, AsyncSchema


def response_json(response):
    return json.loads(response.body.decode())


j = lambda **kwargs: json.dumps(kwargs)
jl = lambda **kwargs: json.dumps([kwargs])


@pytest.mark.parametrize('view,expected', [
    (GraphQLView(schema=Schema), False),
    (GraphQLView(schema=Schema, executor=SyncExecutor()), False),
    (GraphQLView(schema=Schema, executor=AsyncioExecutor()), True),
])
def test_eval(view, expected):
    assert view._enable_async == expected


@pytest.mark.parametrize('app', [
    (create_app(async_executor=False)),
    (create_app(async_executor=True)),
])
def test_allows_get_with_query_param(app):
    _, response = app.client.get(uri=url_string(query='{test}'))

    assert response.status == 200