aiohttp.web.Application

Here are the examples of the python api aiohttp.web.Application taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

138 Examples 7

Example 1

Project: aiohttp
License: View license
Source File: web_srv.py
async def init(loop):
    app = Application(loop=loop)
    app.router.add_get('/', intro)
    app.router.add_get('/simple', simple)
    app.router.add_get('/change_body', change_body)
    app.router.add_get('/hello/{name}', hello)
    app.router.add_get('/hello', hello)
    return app

Example 2

Project: aiohttp
License: View license
Source File: test_run_app.py
def test_run_app_nondefault_host_port(loop, unused_port, mocker):
    port = unused_port()
    host = 'localhost'

    mocker.spy(loop, 'create_server')
    loop.call_later(0.05, loop.stop)

    app = web.Application(loop=loop)
    mocker.spy(app, 'startup')

    web.run_app(app, host=host, port=port, print=lambda *args: None)

    assert loop.is_closed()
    loop.create_server.assert_called_with(mock.ANY, host, port,
                                          ssl=None, backlog=128)
    app.startup.assert_called_once_with()

Example 3

Project: aiohttp_admin
License: View license
Source File: test_admin.py
def test_admin_default_ctor(loop):
    app = web.Application(loop=loop)
    admin = aiohttp_admin.Admin(app, loop=loop)
    assert app is admin.app
    assert admin.name == 'aiohttp_admin'
    assert admin.template == 'admin.html'

Example 4

Project: aiohttp
License: View license
Source File: background_tasks.py
async def init(loop):
    app = Application(loop=loop)
    app['websockets'] = []
    app.router.add_get('/news', websocket_handler)
    app.on_startup.append(start_background_tasks)
    app.on_cleanup.append(cleanup_background_tasks)
    app.on_shutdown.append(on_shutdown)
    return app

Example 5

Project: unicode-solutions
License: View license
Source File: http_charfinder.py
@asyncio.coroutine
def init(loop, address, port):  # <1>
    app = web.Application(loop=loop)  # <2>
    app.router.add_route('GET', '/', home)  # <3>
    handler = app.make_handler()  # <4>
    server = yield from loop.create_server(handler,
                                           address, port)  # <5>
    return server.sockets[0].getsockname()  # <6>

Example 6

Project: aiohttp-session
License: View license
Source File: test_http_exception.py
def create_app(loop, *handlers):
    middleware = session_middleware(SimpleCookieStorage())
    app = web.Application(middlewares=[middleware], loop=loop)
    for url, handler in handlers:
        app.router.add_route('GET', url, handler)
    return app

Example 7

Project: aiohttp
License: View license
Source File: test_connector.py
    @asyncio.coroutine
    def create_unix_server(self, method, path, handler):
        tmpdir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, tmpdir)
        app = web.Application(loop=self.loop)
        app.router.add_route(method, path, handler)

        self.handler = app.make_handler(keep_alive_on=False, access_log=None)
        sock_path = os.path.join(tmpdir, 'socket.sock')
        srv = yield from self.loop.create_unix_server(
            self.handler, sock_path)
        url = "http://127.0.0.1" + path
        self.addCleanup(srv.close)
        return app, srv, url, sock_path

Example 8

Project: aiohttp-cors
License: View license
Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_message_roundtrip(self):
        """Test that aiohttp server is correctly setup in the base class."""

        app = web.Application()

        app.router.add_route("GET", "/", handler)

        yield from self.create_server(app)

        response = yield from aiohttp.request("GET", self.server_url)
        self.assertEqual(response.status, 200)
        data = yield from response.text()

        self.assertEqual(data, TEST_BODY)

Example 9

Project: aiohttp
License: View license
Source File: test_urldispatch.py
def test_subapp_iter(router, loop):
    subapp = web.Application(loop=loop)
    r1 = subapp.router.add_get('/', make_handler())
    r2 = subapp.router.add_post('/', make_handler())
    resource = router.add_subapp('/pre', subapp)
    assert list(resource) == [r1, r2]

Example 10

Project: aiohttp-cors
License: View license
Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_dummy_setup_roundtrip(self):
        """Test a dummy configuration with a message round-trip."""
        app = web.Application()
        setup(app)

        app.router.add_route("GET", "/", handler)

        yield from self.create_server(app)

        response = yield from aiohttp.request("GET", self.server_url)
        self.assertEqual(response.status, 200)
        data = yield from response.text()

        self.assertEqual(data, TEST_BODY)

Example 11

Project: aiohttp
License: View license
Source File: main.py
async def init(loop):
    app = web.Application(loop=loop)
    app['sockets'] = {}
    app.on_shutdown.append(shutdown)

    aiohttp_jinja2.setup(
        app, loader=jinja2.PackageLoader('aiohttpdemo_chat', 'templates'))

    setup_routes(app)

    return app

Example 12

Project: Flask-aiohttp
License: View license
Source File: __init__.py
    def create_aiohttp_app(self, app: flask.Flask) -> aiohttp.web.Application:
        """Create aiohttp web application from Flask application

        :param app: Flask application
        :returns: aiohttp web application

        """
        # aiohttp web application instance
        aio_app = aiohttp.web.Application()

        # WSGI handler for aiohttp
        wsgi_handler = self.handler_factory(app)

        # aiohttp's router should accept any possible HTTP method of request.
        aio_app.router.add_route('*', r'/{path:.*}', wsgi_handler)
        return aio_app

Example 13

Project: aiohttp-jinja2
License: View license
Source File: test_jinja_globals.py
def test_get_env(loop):
    app = web.Application(loop=loop)
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': "tmpl"}))

    env = aiohttp_jinja2.get_env(app)
    assert isinstance(env, jinja2.Environment)
    assert env is aiohttp_jinja2.get_env(app)

Example 14

Project: aiohttp
License: View license
Source File: web_cookies.py
@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)
    app.router.add_get('/', root)
    app.router.add_get('/login', login)
    app.router.add_get('/logout', logout)
    return app

Example 15

Project: backslant
License: View license
Source File: aioserver.py
@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/{name}', handle)

    srv = yield from loop.create_server(app.make_handler(),
                                        '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv

Example 16

Project: aiohttp
License: View license
Source File: server.py
@asyncio.coroutine
def main(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', wshandler)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 9001)
    print("Server started at http://127.0.0.1:9001")
    return app, srv, handler

Example 17

Project: aiohttp_admin
License: View license
Source File: test_admin.py
def test_get_admin(loop):
    app = web.Application(loop=loop)
    admin = aiohttp_admin.setup(app, './')

    fetched_admin = aiohttp_admin.get_admin(app)
    assert admin is fetched_admin

Example 18

Project: aiohttp
License: View license
Source File: test_run_app.py
def test_run_app_http_access_format(loop, mocker):
    mocker.spy(loop, 'create_server')
    loop.call_later(0.05, loop.stop)

    app = web.Application(loop=loop)
    mocker.spy(app, 'startup')

    web.run_app(app, print=lambda *args: None, access_log_format='%a')

    assert loop.is_closed()
    cs = loop.create_server
    cs.assert_called_with(mock.ANY, '0.0.0.0', 8080, ssl=None, backlog=128)
    assert cs.call_args[0][0]._kwargs['access_log_format'] == '%a'
    app.startup.assert_called_once_with()

Example 19

Project: webargs
License: View license
Source File: aiohttp_example.py
def create_app():
    app = web.Application()
    app.router.add_route('GET', '/', index)
    app.router.add_route('POST', '/add', add)
    app.router.add_route('POST', '/dateadd', dateadd)
    return app

Example 20

Project: aiohttp
License: View license
Source File: test_urldispatch.py
def test_subapp_len(router, loop):
    subapp = web.Application(loop=loop)
    subapp.router.add_get('/', make_handler())
    subapp.router.add_post('/', make_handler())
    resource = router.add_subapp('/pre', subapp)
    assert len(resource) == 2

Example 21

Project: sakia
License: View license
Source File: server.py
    def __init__(self, loop):
        self.lp = loop
        self.requests = []
        self.app = web.Application(loop=self.lp,
                                   middlewares=[self.middleware_factory])

        self.handler = self.app.make_handler(
            keep_alive_on=False,
            access_log=log.access_logger,
        )

        self.port = self.find_unused_port()

Example 22

Project: server
License: View license
Source File: control.py
@asyncio.coroutine
def init(loop, player_service, game_service):
    """
    Initialize the http control server
    """
    ctrl_server = ControlServer(game_service, player_service)
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/games', ctrl_server.games)
    app.router.add_route('GET', '/players', ctrl_server.players)
    app.router.add_route('POST', '/players/{player_id}', ctrl_server.kick_player)

    srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 4040)
    logger.info("Control server listening on http://127.0.0.1:4040")
    return srv

Example 23

Project: hammock
License: View license
Source File: __init__.py
def get(api, **kwargs):
    if api == hammock.FALCON:
        api = falcon.API(**kwargs)
        return _falcon.Falcon(api)
    elif api == hammock.AWEB:
        import aiohttp.web as aweb  # pylint: disable=import-error
        api = aweb.Application(**kwargs)
        return _aweb.AWeb(api)
    elif falcon and isinstance(api, falcon.API):
        return _falcon.Falcon(api)
    else:
        raise RuntimeError('Invalid API given, or api library not available.')

Example 24

Project: concorrente.py
License: View license
Source File: http_charfinder.py
@asyncio.coroutine
def init(loop, address, port):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handle)

    server = yield from loop.create_server(app.make_handler(),
                                           address, port)
    host = server.sockets[0].getsockname()
    print('Serving on {}. Hit CTRL-C to stop.'.format(host))

Example 25

Project: aiohttp-cors
License: View license
Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_dummy_setup_roundtrip_resource(self):
        """Test a dummy configuration with a message round-trip."""
        app = web.Application()
        setup(app)

        app.router.add_resource("/").add_route("GET", handler)

        yield from self.create_server(app)

        response = yield from aiohttp.request("GET", self.server_url)
        self.assertEqual(response.status, 200)
        data = yield from response.text()

        self.assertEqual(data, TEST_BODY)

Example 26

Project: vyked
License: View license
Source File: host.py
    @classmethod
    def _make_aiohttp_handler(cls):
        app = Application(loop=asyncio.get_event_loop())
        for each in cls._http_service.__ordered__:
            # iterate all attributes in the service looking for http endpoints and add them
            fn = getattr(cls._http_service, each)
            if callable(fn) and getattr(fn, 'is_http_method', False):
                for path in fn.paths:
                    app.router.add_route(fn.method, path, fn)
                    if cls._http_service.cross_domain_allowed:
                        # add an 'options' for this specific path to make it CORS friendly
                        app.router.add_route('options', path, cls._http_service.preflight_response)
        handler = app.make_handler(access_log=cls._logger)
        return handler

Example 27

Project: linked-data-fragments
License: View license
Source File: server.py
@asyncio.coroutine
def init_http_server(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', handle_triple)
    server = yield from loop.create_server(app.make_handler(),
                                           config.get('host'), 
                                           config.get('port'))
    if config.get('debug'):
        print("Running HTTP Server at {} {}".format(config.get('host'), 
                                                    config.get('port')))
    return server

Example 28

    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)

        self.adapter = ResourcesUrlDispatcherRouterAdapter(
            self.app.router, defaults={
                "*": ResourceOptions()
            })
        self.get_route = self.app.router.add_route(
            "GET", "/get_path", _handler)
        self.options_route = self.app.router.add_route(
            "OPTIONS", "/options_path", _handler)

Example 29

Project: aiohttp
License: View license
Source File: fake_server.py
    def __init__(self, *, loop):
        self.loop = loop
        self.app = web.Application(loop=loop)
        for name in dir(self.__class__):
            func = getattr(self.__class__, name)
            if hasattr(func, '__method__'):
                self.app.router.add_route(func.__method__,
                                          func.__path__,
                                          getattr(self, name))
        self.handler = None
        self.server = None
        here = pathlib.Path(__file__)
        ssl_cert = here.parent / 'server.crt'
        ssl_key = here.parent / 'server.key'
        self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        self.ssl_context.load_cert_chain(str(ssl_cert), str(ssl_key))

Example 30

Project: aioreactive
License: View license
Source File: autocomplete.py
async def init(loop):
    port = os.environ.get("PORT", 8080)
    host = "localhost"
    app = web.Application(loop=loop)
    print("Starting server at port: %s" % port)

    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('.'))
    app.router.add_static('/static', "static")
    app.router.add_get('/', index)
    app.router.add_get('/ws', websocket_handler)

    return app, host, port

Example 31

Project: aiohttp
License: View license
Source File: web_classview1.py
async def init(loop):
    app = Application(loop=loop)
    app.router.add_get('/', index)
    app.router.add_get('/get', MyView)
    app.router.add_post('/post', MyView)
    return app

Example 32

@pytest.fixture
def make_app(loop):
    app = web.Application(loop=loop)
    setup_session(app, SimpleCookieStorage())
    setup_security(app, SessionIdentityPolicy(), Autz())
    return app

Example 33

@asyncio.coroutine
def init(loop):
    app = Application(loop=loop, middlewares=[middleware_factory])
    app.router.add_get('/', handler)

    requests_handler = app.make_handler()
    srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, requests_handler

Example 34

Project: aiohttp_utils
License: View license
Source File: test_runner.py
    def test_reload_override(self):
        app = web.Application(debug=True)
        assert Runner(app, reload=False).reload is False

        app = web.Application(debug=False)
        assert Runner(app, reload=True, app_uri='foo').reload is True

Example 35

Project: aiohttp
License: View license
Source File: web_ws.py
async def init(loop):
    app = Application(loop=loop)
    app['sockets'] = []
    app.router.add_get('/', wshandler)
    app.on_shutdown.append(on_shutdown)
    return app

Example 36

Project: aiohttp-session
License: View license
Source File: test_redis_storage.py
def create_app(loop, handler, redis, max_age=None):
    middleware = session_middleware(
        RedisStorage(redis, max_age=max_age))
    app = web.Application(middlewares=[middleware], loop=loop)
    app.router.add_route('GET', '/', handler)
    return app

Example 37

Project: aiohttp
License: View license
Source File: test_connector.py
    @asyncio.coroutine
    def create_server(self, method, path, handler):
        app = web.Application(loop=self.loop)
        app.router.add_route(method, path, handler)

        port = unused_port()
        self.handler = app.make_handler(keep_alive_on=False)
        srv = yield from self.loop.create_server(
            self.handler, '127.0.0.1', port)
        url = "http://127.0.0.1:{}".format(port) + path
        self.addCleanup(srv.close)
        return app, srv, url

Example 38

Project: aiohttp-cors
License: View license
Source File: test_main.py
    @asyncio.coroutine
    def create_server(self, app: web.Application):
        """Create server listening on random port."""

        assert self.app is None
        self.app = app

        assert self.handler is None
        self.handler = app.make_handler()

        self.server = (yield from create_server(self.handler, self.loop))

        return self.server

Example 39

Project: aiohttp
License: View license
Source File: test_run_app.py
def test_run_app_http(loop, mocker):
    mocker.spy(loop, 'create_server')
    loop.call_later(0.05, loop.stop)

    app = web.Application(loop=loop)
    mocker.spy(app, 'startup')

    web.run_app(app, print=lambda *args: None)

    assert loop.is_closed()
    loop.create_server.assert_called_with(mock.ANY, '0.0.0.0', 8080,
                                          ssl=None, backlog=128)
    app.startup.assert_called_once_with()

Example 40

Project: aiohttp_admin
License: View license
Source File: test_admin.py
def test_get_admin_with_app_key(loop):
    app = web.Application(loop=loop)
    app_key = 'other_place'
    admin = aiohttp_admin.setup(app, './', app_key=app_key)

    fetched_admin = aiohttp_admin.get_admin(app, app_key=app_key)
    assert admin is fetched_admin

Example 41

Project: aiohttp
License: View license
Source File: test_run_app.py
def test_run_app_https(loop, mocker):
    mocker.spy(loop, 'create_server')
    loop.call_later(0.05, loop.stop)

    app = web.Application(loop=loop)
    mocker.spy(app, 'startup')

    ssl_context = ssl.create_default_context()

    web.run_app(app, ssl_context=ssl_context, print=lambda *args: None)

    assert loop.is_closed()
    loop.create_server.assert_called_with(mock.ANY, '0.0.0.0', 8443,
                                          ssl=ssl_context, backlog=128)
    app.startup.assert_called_once_with()

Example 42

Project: aiohttp-devtools
License: View license
Source File: test_runserver.py
async def test_run_app(loop, tmpworkdir, test_client):
    mktree(tmpworkdir, SIMPLE_APP)
    app = create_main_app(app_path='app.py', loop=loop)
    assert isinstance(app, aiohttp.web.Application)
    cli = await test_client(app)
    r = await cli.get('/')
    assert r.status == 200
    text = await r.text()
    assert text == 'hello world'

Example 43

Project: aiohttp
License: View license
Source File: test_run_app.py
def test_run_app_custom_backlog(loop, mocker):
    mocker.spy(loop, 'create_server')
    loop.call_later(0.05, loop.stop)

    app = web.Application(loop=loop)
    mocker.spy(app, 'startup')

    web.run_app(app, backlog=10, print=lambda *args: None)

    assert loop.is_closed()
    loop.create_server.assert_called_with(mock.ANY, '0.0.0.0', 8080,
                                          ssl=None, backlog=10)
    app.startup.assert_called_once_with()

Example 44

Project: aiohttp_admin
License: View license
Source File: test_admin.py
def test_admin_ctor(loop):
    app = web.Application(loop=loop)
    name = 'custom admin name'
    template = 'other.html'
    admin = aiohttp_admin.Admin(app, name=name, template=template, loop=loop)
    assert app is admin.app
    assert name == admin.name
    assert template == admin.template

Example 45

Project: aiohttp-cors
License: View license
Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_dummy_setup(self):
        """Test a dummy configuration."""
        app = web.Application()
        setup(app)

        yield from self.create_server(app)

Example 46

Project: aiohttp-devtools
License: View license
Source File: main.py
def create_app(loop):
    app = web.Application(loop=loop)
    app['name'] = '{{ name }}'
    app.update(load_settings())
    # {% if template_engine.is_jinja2 %}

    jinja2_loader = jinja2.FileSystemLoader(str(THIS_DIR / 'templates'))
    aiohttp_jinja2.setup(app, loader=jinja2_loader, app_key=JINJA2_APP_KEY)
    app[JINJA2_APP_KEY].filters.update(
        url=reverse_url,
        static=static_url,
    )
    # {% endif %}
    # {% if database.is_postgres_sqlalchemy %}
    app.on_startup.append(startup)
    app.on_cleanup.append(cleanup)
    # {% endif %}
    setup_routes(app)
    return app

Example 47

Project: netwrok-server
License: View license
Source File: ipn.py
@asyncio.coroutine
def init(loop):
    global handler
    app = Application(loop=loop)
    app.router.add_route('GET', '/', handle_get)
    app.router.add_route('POST', '/IPN', handle_ipn)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '0.0.0.0', 8080)
    logging.info("IPN Server started at http://0.0.0.0:8080")

Example 48

Project: cocrawler
License: View license
Source File: webserver.py
def make_app(loop, config):
    # TODO switch this to socket.getaddrinfo() -- see https://docs.python.org/3/library/socket.html
    serverip = config['REST'].get('ServerIP')
    serverport = int(config['REST'].get('ServerPort', '8081'))
    if serverip is None:
        return None

    app = web.Application()
    app.router.add_get('/', frontpage)
    app.router.add_get('/api/{name}', api)

    handler = app.make_handler()
    f = loop.create_server(handler, serverip, serverport)
    srv = loop.run_until_complete(f)
    print('REST serving on', srv.sockets[0].getsockname())

    app['cocrawler'] = handler, srv, loop
    return app

Example 49

Project: aiohttp-cors
License: View license
Source File: test_cors_config.py
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)
        self.cors = CorsConfig(self.app, defaults={
            "*": ResourceOptions()
        })
        self.get_route = self.app.router.add_route(
            "GET", "/get_path", _handler)
        self.options_route = self.app.router.add_route(
            "OPTIONS", "/options_path", _handler)

Example 50

Project: wechatpy
License: View license
Source File: app.py
@asyncio.coroutine
def main(loop):
    app = Application(loop=loop)
    app.router.add_route('GET', '/', user_info)
    app.router.add_route('GET', '/group_id', user_group_id)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 8888)
    print("Server started at http://127.0.0.1:8888")
    return srv, handler
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3