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
3
Example 1
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
3
Example 2
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()
3
Example 3
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'
3
Example 4
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
3
Example 5
@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>
3
Example 6
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
3
Example 7
@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
3
Example 8
Project: aiohttp-cors
License: View license
Source File: test_main.py
Function: test_message_round_trip
License: View license
Source File: test_main.py
Function: test_message_round_trip
@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)
3
Example 9
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]
3
Example 10
@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)
3
Example 11
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
3
Example 12
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
3
Example 13
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)
3
Example 14
@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
3
Example 15
@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
3
Example 16
@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
3
Example 17
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
3
Example 18
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()
3
Example 19
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
3
Example 20
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
3
Example 21
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()
3
Example 22
@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
3
Example 23
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.')
3
Example 24
@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))
3
Example 25
@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)
3
Example 26
@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
3
Example 27
@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
3
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)
3
Example 29
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))
3
Example 30
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
3
Example 31
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
3
Example 32
@pytest.fixture
def make_app(loop):
app = web.Application(loop=loop)
setup_session(app, SimpleCookieStorage())
setup_security(app, SessionIdentityPolicy(), Autz())
return app
3
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
3
Example 34
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
3
Example 35
async def init(loop):
app = Application(loop=loop)
app['sockets'] = []
app.router.add_get('/', wshandler)
app.on_shutdown.append(on_shutdown)
return app
3
Example 36
Project: aiohttp-session
License: View license
Source File: test_redis_storage.py
Function: create_app
License: View license
Source File: test_redis_storage.py
Function: create_app
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
3
Example 37
@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
3
Example 38
@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
3
Example 39
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()
3
Example 40
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
3
Example 41
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()
3
Example 42
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'
3
Example 43
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()
3
Example 44
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
3
Example 45
@asynctest
@asyncio.coroutine
def test_dummy_setup(self):
"""Test a dummy configuration."""
app = web.Application()
setup(app)
yield from self.create_server(app)
3
Example 46
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
3
Example 47
@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")
3
Example 48
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
3
Example 49
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)
3
Example 50
@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