Ejemplo n.º 1
0
def get_app():
    model = Model()
    app = web.Application()
    app.router.add_routes(all_routes)
    app['model'] = model
    GraphQLView.attach(app,
                       route_path='/api/graphql',
                       schema=Schema,
                       graphiql=True,
                       enable_async=True,
                       executor=GQLAIOExecutor())

    subscription_server = AiohttpSubscriptionServer(Schema)

    async def subscriptions(request):
        try:
            ws = web.WebSocketResponse(protocols=('graphql-ws', ))
            await ws.prepare(request)
            await subscription_server.handle(ws, {'request': request})
            return ws
        except Exception as e:
            logger.exception('subscriptions failed: %r', e)
            raise e

    app.router.add_get('/api/subscriptions', subscriptions)
    return app
Ejemplo n.º 2
0
    def wsgi_app(self):
        """This method defines all the necesarry to be called from the wsgi"""
        self.build()
        app = web.Application()

        # configure route
        GraphQLView.attach(app,
                           schema=self.schema(),
                           field_resolver=self._resolver,
                           batch=True,
                           graphiql=True)

        if self.config.get('API_CORS', False):
            # enable CORS
            cors = aiohttp_cors.setup(
                app,
                defaults={
                    "*":
                    aiohttp_cors.ResourceOptions(
                        allow_credentials=True,
                        expose_headers=("X-Custom-Server-Header", ),
                        allow_headers=("X-Requested-With", "Content-Type"),
                        max_age=3600,
                    )
                })
            #get_route = app.router.add_route('GET', '/graphql', handler, name='graphql')
            #post_route = app.router.add_route('POST', '/graphql', handler, name='graphql')

            #cors.add(get_route)
            #cors.add(post_route)

        return app
Ejemplo n.º 3
0
async def async_main(conf):
    async with AsyncExitStack() as stack:
        alert_webhooks = await stack.enter_async_context(
            AlertWebhooks(conf.alert_webhooks))
        model = await stack.enter_async_context(
            get_model(conf, alert_webhooks=alert_webhooks))
        alert_webhooks.set_model(model)
        app = Application()
        app['model'] = model
        app.router.add_routes(routes)
        GraphQLView.attach(app,
                           route_path='/graphql',
                           schema=graphql_schema,
                           graphiql=True,
                           enable_async=True,
                           executor=GQLAIOExecutor())
        runner = AppRunner(app)
        await runner.setup()
        host = conf.http_interface.bind_host
        port = conf.http_interface.bind_port
        site = TCPSite(runner, host, port)
        await site.start()
        stop_event = asyncio.Event()
        asyncio.get_running_loop().add_signal_handler(SIGINT, stop_event.set)
        asyncio.get_running_loop().add_signal_handler(SIGTERM, stop_event.set)
        logger.debug('Listening on http://%s:%s', host or 'localhost', port)
        await stop_event.wait()
        logger.debug('Cleanup...')
        t = asyncio.create_task(log_still_running_tasks())
        await runner.cleanup()
        t.cancel()
        logger.debug('Cleanup done')
Ejemplo n.º 4
0
async def async_launch_web():
    app.add_routes(routes)
    logger.debug(
        f'Launch web interface on {config.api.host}:{config.api.port}')
    GraphQLView.attach(app, schema=schema, graphiql=True)
    # await web._run_app(app, port=config['api']['port'])
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, '127.0.0.1', config.api.port)
    await site.start()
Ejemplo n.º 5
0
def make_app():
    fernet_key = fernet.Fernet.generate_key()
    secret_key = base64.urlsafe_b64decode(fernet_key)
    storage = EncryptedCookieStorage(secret_key=secret_key)
    session_midl = session_middleware(storage)
    middlewares = [session_midl]
    app = web.Application(loop=loop, middlewares=middlewares)

    setup(app, EncryptedCookieStorage(secret_key=secret_key))
    app.on_startup.append(init_db)
    GraphQLView.attach(app, schema=schema, graphiql=True, enable_async=True)
    app['config'] = conf['db']
    setup_routes(app)
    app.on_cleanup.append(close_db)
    return app
Ejemplo n.º 6
0
def app(executor, view_kwargs):
    app = web.Application()
    GraphQLView.attach(app, executor=executor, **view_kwargs)
    return app
Ejemplo n.º 7
0
            'set_articles_read': GraphQLField(
                type=GraphQLInt,
                resolver=set_articles_read_resolver
            )
        }
    )
)


async def enable_cors(_request, response):
    response.headers['Access-Control-Allow-Headers'] = 'content-type'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Origin'] = 'http://localhost'
    response.headers['Access-Control-Max-Age'] = '86400'


app = web.Application()

app.on_response_prepare.append(enable_cors)

GraphQLView.attach(
    app,
    schema=schema,
    graphiql=True,
    route_path='/gql',
    executor=AsyncioExecutor(),
    enable_async=True
)

web.run_app(app, port=3081)
Ejemplo n.º 8
0
from aiohttp import web
from aiohttp_graphql import GraphQLView
from graphql.execution.executors.asyncio import AsyncioExecutor

from schema import schema

app = web.Application()
GraphQLView.attach(app,
                   schema=schema,
                   executor=AsyncioExecutor(),
                   graphiql=True,
                   pretty=True)

web.run_app(app)
Ejemplo n.º 9
0
def create_app(schema=Schema, **kwargs):
    app = web.Application()
    # Only needed to silence aiohttp deprecation warnings
    GraphQLView.attach(app, schema=schema, **kwargs)
    return app
Ejemplo n.º 10
0
    full_name = String()


class Queries(graphene.ObjectType):

    person = graphene.Field(Person, input=InputPerson())

    # person = graphene.Field(Person, first_name=graphene.String(), last_name=graphene.NonNull(graphene.String))

    def resolve_person(self, *args, input: InputPerson, **kwargs):
        result = Person()
        result.first_name = input.first_name
        result.last_name = input.last_name
        result.full_name = f"{input.first_name} {input.last_name}"

        return result

    # def resolve_person(self, *args, first_name='', last_name='', **kwargs):
    #     result = Person()
    #     result.first_name = first_name
    #     result.last_name = last_name
    #     result.full_name = f"{first_name} {last_name}"
    #
    #     return result


Schema = Schema(query=Queries)
app = web.Application()

GraphQLView.attach(app, schema=Schema, graphiql=True)
web.run_app(app, port=5002)
Ejemplo n.º 11
0
    lname = info.get('lname')
    if fname == '' or lname == '':
        #        print("403")
        return web.Response(text="ERROR 403")


#    print("name:  ", fname, "\n")
#    print("lname: ", lname, "\n")
    response = await handler(request)
    return response

app = web.Application(middlewares=[my_first_middl])
app.add_routes([
    web.get('/index', index_handle),
    web.get('/echo', wshandle),
    web.get('/settings', settings_handle),
    web.get('/test', test_handle),
    web.get('/login', login_handle),
    web.post('/verify', verify_handle),
    web.get('/edit', edit_handle)
])

#for route in routes:
#        app.router.add_route(route[0], route[1], route[2])

aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates/'))

GraphQLView.attach(app, schema=AsyncShema, graphiql=True)

web.run_app(app)
Ejemplo n.º 12
0
def setup_routes(app):
    app.add_routes([
        web.get('/search', search),
    ])
    GraphQLView.attach(app, schema=schema, route_path='/graphql',
                       executor=AsyncioExecutor(asyncio.get_event_loop()))
Ejemplo n.º 13
0
from aiohttp.web import Application, RouteTableDef, Response
from aiohttp_graphql import GraphQLView
from graphql.execution.executors.asyncio import AsyncioExecutor
from motor.motor_asyncio import AsyncIOMotorClient
import os
from .graphql import graphql_schema
from .model import Model

routes = RouteTableDef()

@routes.get('/')
def index(request):
    return Response(text='Hello World! This is polls_backend.\n')

application = Application()
application.add_routes(routes)
GraphQLView.attach(application, schema=graphql_schema, graphiql=True, executor=AsyncioExecutor())

# example how the full connection (MONGO_URI) string looks like:
# "mongodb+srv://user0:[email protected]/test?retryWrites=true&w=majority"

client = AsyncIOMotorClient(os.environ.get('MONGO_URI') or 'mongodb://127.0.0.1:27017')
db_name = os.environ.get('MONGO_DB_NAME') or 'poll_app'
db = client[db_name]

application['model'] = Model(db)
Ejemplo n.º 14
0
def app(view_kwargs):
    app = web.Application()
    GraphQLView.attach(app, **view_kwargs)
    return app