aiohttp-security/demo/database_auth/main.py

61 lines
1.8 KiB
Python
Raw Permalink Normal View History

2015-11-26 18:09:00 +00:00
import asyncio
2020-12-18 17:58:38 +00:00
from typing import Any, Tuple
2015-11-26 18:09:00 +00:00
from aiohttp import web
from aiohttp_session import setup as setup_session
from aiohttp_session.redis_storage import RedisStorage
from aiohttp_security import setup as setup_security
from aiohttp_security import SessionIdentityPolicy
from aiopg.sa import create_engine
from aioredis import create_pool
from demo.database_auth.db_auth import DBAuthorizationPolicy
from demo.database_auth.handlers import Web
2015-11-26 18:09:00 +00:00
2020-12-18 17:58:38 +00:00
async def init(loop: asyncio.AbstractEventLoop) -> Tuple[Any, ...]:
2017-12-13 14:51:46 +00:00
redis_pool = await create_pool(('localhost', 6379))
db_engine = await create_engine(user='aiohttp_security',
password='aiohttp_security',
database='aiohttp_security',
host='127.0.0.1')
2018-09-06 10:06:55 +00:00
app = web.Application()
2020-12-18 17:58:38 +00:00
app['db_engine'] = db_engine
2015-11-26 18:09:00 +00:00
setup_session(app, RedisStorage(redis_pool))
setup_security(app,
SessionIdentityPolicy(),
DBAuthorizationPolicy(db_engine))
2015-11-26 18:09:00 +00:00
2015-11-30 12:58:49 +00:00
web_handlers = Web()
web_handlers.configure(app)
2015-11-26 18:09:00 +00:00
handler = app.make_handler()
2017-12-13 14:51:46 +00:00
srv = await loop.create_server(handler, '127.0.0.1', 8080)
print('Server started at http://127.0.0.1:8080')
2015-11-26 18:26:57 +00:00
return srv, app, handler
2015-11-26 18:09:00 +00:00
2020-12-18 17:58:38 +00:00
async def finalize(srv: Any, app: Any, handler: Any) -> None:
2015-11-26 18:26:57 +00:00
sock = srv.sockets[0]
app.loop.remove_reader(sock.fileno())
sock.close()
2017-12-13 14:51:46 +00:00
await handler.finish_connections(1.0)
2015-11-26 18:26:57 +00:00
srv.close()
2017-12-13 14:51:46 +00:00
await srv.wait_closed()
await app.finish()
2015-11-26 18:09:00 +00:00
2020-12-18 17:58:38 +00:00
def main() -> None:
2016-02-01 17:25:14 +00:00
loop = asyncio.get_event_loop()
srv, app, handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete((finalize(srv, app, handler)))
if __name__ == '__main__':
main()