How to use the aiohttp.web.Application function in aiohttp

To help you get started, we’ve selected a few aiohttp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aio-libs / aiohttp / tests / test_web_app.py View on Github external
sub = web.Application()
    root.add_subapp('/sub', sub)
    root.freeze()
    assert root._run_middlewares is False

    @web.middleware
    async def middleware(request, handler):
        return await handler(request)

    root = web.Application(middlewares=[middleware])
    sub = web.Application()
    root.add_subapp('/sub', sub)
    root.freeze()
    assert root._run_middlewares is True

    root = web.Application()
    sub = web.Application(middlewares=[middleware])
    root.add_subapp('/sub', sub)
    root.freeze()
    assert root._run_middlewares is True
github asvetlov / us-pycon-2019-tutorial / code / 10-testing / proj / server.py View on Github external
async def init_app(db_path: Path) -> web.Application:
    app = web.Application(client_max_size=64 * 1024 ** 2)
    app["DB_PATH"] = db_path
    app.add_routes(router)
    app.cleanup_ctx.append(init_db)
    aiohttp_session.setup(app, aiohttp_session.SimpleCookieStorage())
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates")),
        context_processors=[username_ctx_processor],
    )
    app.middlewares.append(error_middleware)
    app.middlewares.append(check_login)

    return app
github aio-libs / aiohttp-cors / tests / integration / test_main.py View on Github external
def inner(defaults, route_config):
        app = web.Application()
        cors = _setup(app, defaults=defaults)

        if request.param == 'resource':
            resource = cors.add(app.router.add_resource("/resource"))
            cors.add(resource.add_route("GET", handler), route_config)
        elif request.param == 'view':
            WebViewHandler.cors_config = route_config
            cors.add(
                app.router.add_route("*", "/resource", WebViewHandler))
        elif request.param == 'route':
            cors.add(
                app.router.add_route("GET", "/resource", handler),
                route_config)
        else:
            raise RuntimeError('unknown parameter {}'.format(request.param))
github foglamp / FogLAMP / tests / unit / python / foglamp / services / core / api / test_support.py View on Github external
def client(self, loop, test_client):
        app = web.Application(loop=loop)
        # fill the routes table
        routes.setup(app)
        return loop.run_until_complete(test_client(app))
github aio-libs / aiohttp_admin / demos / motortwit / motortwit / main.py View on Github external
async def init(loop):
    conf = load_config(str(PROJ_ROOT / 'config' / 'config.yml'))

    app = web.Application(loop=loop)
    cookie_storage = SimpleCookieStorage()
    app = web.Application(middlewares=[session_middleware(cookie_storage)])
    mongo = await setup_mongo(app, conf, loop)

    setup_jinja(app)

    admin = setup_admin(app, mongo)
    app.add_subapp('/admin', admin)

    app.router.add_static('/static', path=str(PROJ_ROOT / 'static'))

    # setup views and routes
    handler = SiteHandler(mongo)
    setup_routes(app, handler, PROJ_ROOT)

    host, port = conf['host'], conf['port']
    return app, host, port
github rockstat / band-framework / band / server.py View on Github external
from aiohttp import web
import uvloop
import asyncio

from .log import logger
from .lib.http import naive_cors_middleware, error_middleware
from . import dome, loop

__all__ = ['add_routes', 'start_server', 'app']


# loop = uvloop.new_event_loop()
# loop.set_exception_handler(loop_exc)
# asyncio.set_event_loop(loop)

app = web.Application(
    logger=logger, debug=False, middlewares=[naive_cors_middleware, error_middleware])


def add_routes(routes):
    logger.debug('Attaching routes')
    app.router.add_routes(routes)


def start_server(listen, name, **kwargs):
    host, port = listen.split(':')
    add_routes(dome.routes)

    web.run_app(app, host=host, port=port, handle_signals=True, print=None, access_log=None)
github TurtleRover / tcs / server / http_server.py View on Github external
def __init__(self):
        self.SERVER_DIR = os.path.dirname(os.path.abspath(__file__))
        self.PROJECT_DIR = os.path.join( os.path.dirname( __file__ ), '..' )
    
        self.app = web.Application()
github Trim21 / bgm-tv-auto-tracker / server / app.py View on Github external
def create_app(io_loop=asyncio.get_event_loop()):
    app: TypeApp = web.Application(middlewares=[])
    if DSN:
        from aiohttp_sentry import SentryMiddleware
        app.middlewares.append(
            SentryMiddleware({
                'environment': 'foo',
                'release': 'bar',
                'ignore_exceptions': [web.HTTPException],
                'dsn': DSN,
            }),
        )
    app.tz = pytz.timezone('Asia/Shanghai')
    app.on_cleanup.append(clean_up)
    app.client_session = aiohttp.ClientSession(loop=io_loop)
    setup_mongo(app, io_loop)

    aiohttp_session.setup(
github algoo / hapic / example / example_a_aiohttp.py View on Github external
data = hapic_data.body
    return {
        'data': data,
    }


async def do_login(request):
    data = await request.json()
    login = data['login']
    password = data['password']

    return web.json_response({
        'login': login,
    })

app = web.Application(debug=True)
app.add_routes([
    web.get('/n/', display_name),
    web.get('/n/{name}', display_name),
    web.post('/n/{name}', display_name),
    web.post('/b/', display_body),
    web.post('/login', do_login),
])


hapic.set_context(AiohttpContext(app, default_error_builder=MarshmallowDefaultErrorBuilder()))


# import json
# import yaml
# print(yaml.dump(
#     json.loads(json.dumps(hapic.generate_doc())),
github hyperledger / aries-staticagent-python / examples / webserver_with_websockets.py View on Github external
await sock.close()

        return sock

    async def post_handle(request):
        """Handle posted messages."""
        response = []
        with conn.session(response.append) as session:
            await conn.handle(await request.read(), session)

        if response:
            return web.Response(text=response.pop())

        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([
        web.get('/', ws_handle),
        web.post('/', post_handle)
    ])

    web.run_app(app, port=args.port)