def run(): app = web.Application() fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) setup(app, EncryptedCookieStorage(secret_key)) app.router.add_route('*', '/{name}', view) web.run_app(app, host='0.0.0.0', port=port)
def create_app(): app = web.Application() settings = Settings() app.update(name='{{ name }}', settings=settings) # {% if template_engine.is_jinja %} 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_pg_sqlalchemy %} app.on_startup.append(startup) app.on_cleanup.append(cleanup) # {% endif %} # {% if session.is_secure %} secret_key = base64.urlsafe_b64decode(settings.COOKIE_SECRET) aiohttp_session.setup(app, EncryptedCookieStorage(secret_key)) # {% endif %} setup_routes(app) return app
def run(self): from aiohttp_session import setup from aiohttp_session.cookie_storage import EncryptedCookieStorage from cryptography.fernet import Fernet from aiohttp_jinja2 import setup as jinja_setup import aiohttp_jinja2 asyncio.set_event_loop(self.loop) # Setting up symmetric cookie encryption using # Fernet that guarantees that a message encrypted # using it cannot be manipulated or read without the key setup( self.application, EncryptedCookieStorage( base64.urlsafe_b64decode(Fernet.generate_key()))) self.application.add_routes(self.routes) # Running the webserver using the host # and port configurations, and the web application server = self.loop.create_server(self.application.make_handler(), self.host, self.port) print('========== Webserver running on: http://%s:%d/ ==========' % (self.host, self.port)) # using asyncio to gather the processes as tasks and run # them separately in foreground and background try: self.loop.run_until_complete(asyncio.gather(server)) self.loop.run_forever() except: exit('Failed at startup.')
def start(): """Start Web server.""" config = OrganiserConfiguration() asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = web.Application(debug=config.server.debug) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader( resource_filename(Requirement.parse('organiser'), 'organiser/templates')), auto_reload=config.server.debug, context_processors=[aiohttp_login.flash.context_processor]) aiohttp_session.setup( app, EncryptedCookieStorage(config.server.session_secret, max_age=config.server.session_max_age)) app.middlewares.append(aiohttp_login.flash.middleware) app['db_client'] = AsyncIOMotorClient() app['db'] = app['db_client'].organiser auth_settings = {} for setting in config.authentication: auth_settings[setting.upper()] = config.authentication[setting] aiohttp_login.setup(app, MotorStorage(app['db']), auth_settings) app.router.add_static("/static/", path=Path(__file__) / ".." / "static", name="static") app.router.add_get("/", index_handler) app.router.add_get("/calendar/{period}/", calendar_handler) app.router.add_get("/calendar/{period}/{date}/", calendar_handler) app.router.add_get("/lists/", list_handler) web.run_app(app, host=config.server.ip, port=config.server.port) cleanup_resources()
def prepare(self): if not self.prepared: for method, path, obj in self.router: self.app.router.add_route(method, path, obj) aiohttp_session.setup( self.app, aiohttp_session.cookie_storage.EncryptedCookieStorage(self.session_encrypt_key)) self._prepared = True
async def init_app() -> aiohttp.web.Application: """ Prepare app to run (setup all settings and create db connection). :return: configured instance of the web application :rtype: aiohttp.web.Application """ app = aiohttp.web.Application() # set logger logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # setup Jinja2 template renderer aiohttp_jinja2.setup( app, loader=jinja2.PackageLoader('core') ) # create db connection on startup, shutdown on exit app.on_startup.append(init_mysql) app.on_cleanup.append(close_mysql) # setup views and routes setup_routes(app) # setup middlewares session_redis_storage = await create_session_redis_storage() aiohttp_session.setup(app, session_redis_storage) setup_middlewares(app) return app
def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.add_routes([ web.static('/static/', './static/'), web.get('/', self.main_handler, name='list_rooms'), web.route('*', '/new/', self.new_handler, name='create_room'), web.route('*', '/login/', self.login_handler, name='login'), web.route('*', '/register/', self.register_handler, name='register'), web.route('*', '/edit-profile/', self.edit_profile_handler, name='edit_profile'), web.get('/logout/', self.logout_handler, name='logout'), web.get('/{room}/', self.room_handler, name='room_page'), web.get('/{room}/ws/', self.websocket_handler, name='room_ws'), ]) try: with open('secret_key', 'rb') as fp: secret_key = fp.read() except OSError: fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) with open('secret_key', 'wb') as fp: fp.write(secret_key) setup(self, EncryptedCookieStorage(secret_key)) self.env = jinja2.Environment( loader=jinja2.FileSystemLoader('./templates'), autoescape=True) self.rsa = RsaUtil() self.storage = Storage()
def app_factory(client_id: str, client_secret: str, redirect_uri: str) -> web.Application: app = web.Application() # Add the main routes to the app app.router.add_get("/", index, name="index") app.router.add_get("/me", me, name="me") # Set up the Spotify app to instigate the OAuth flow app["spotify_app"] = aiohttp_spotify.spotify_app( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, handle_auth=update_auth, default_redirect=app.router["index"].url_for(), ) app.add_subapp("/spotify", app["spotify_app"]) # Set up the user session secret_key = base64.urlsafe_b64decode(fernet.Fernet.generate_key()) aiohttp_session.setup(app, EncryptedCookieStorage(secret_key)) # Add the ClientSession to the app app.cleanup_ctx.append(client_session) return app
async def init(self, loop, address, port): handler = self.app.make_handler() for method, path, obj in self.router: self.app.router.add_route(method, path, obj) srv = await loop.create_server(handler, address, port) aiohttp_session.setup(self.app, aiohttp_session.cookie_storage.EncryptedCookieStorage(self.session_encrypt_key)) return srv, handler
async def init(): #App init app = web.Application() #Add full configs app['config'] = setupConfig() #Add routes setupRoutes(app) app['wslist'] = [] #Add static config setupStatic(app) #Jinja config setupJinja(app) #PostgreSQL init app.db = await init_pg(app) #Setup redis REDIS_CONFIG = tuple(app['config']['redis'].values()) redis_pool = await aioredis.create_pool(REDIS_CONFIG, loop=loop) setup(app, RedisStorage(redis_pool)) app['redis'] = await aioredis.create_redis(REDIS_CONFIG) #ShutDown setups app.on_shutdown.append(close_pg) app.on_shutdown.append(close_redis) return app
def make_app(with_db=True) -> Application: app = web.Application() parts = urlparse(URI) setup( app, EncryptedCookieStorage(SECRET_KEY, max_age=MAX_AGE, secure=parts.scheme == "https")) if with_db: app.on_startup.append(init_db) app.on_startup.append(init_state) app.on_shutdown.append(shutdown) app.on_response_prepare.append(on_prepare) # Setup routes. for route in get_routes: app.router.add_get(route[0], route[1]) for route in post_routes: app.router.add_post(route[0], route[1]) app.router.add_static("/static", "static", append_version=True) app.middlewares.append(handle_404) return app
def init_app() -> web.Application: app = web.Application() aiohttp_session.setup(app, EncryptedCookieStorage(settings.SECRET_KEY)) app.router.add_routes(src.views.routes) app['ws'] = [] return app
def main(): app = web.Application() app['websockets'] = {} app['websockets_room'] = {} app['websockets_queue'] = {} app['config'] = SECRET_KEY client = AsyncIOMotorClient(MONGO_HOST) app['db'] = client['AioDB'] app.on_startup.append(start_back_tasks) app.on_startup.append(start_back_tasks_key) app.on_shutdown.append(stop_back_tasks) app.on_shutdown.append(shutdown) fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) aiohttp_jinja2.setup(app, loader=FileSystemLoader(BASE_DIR)) setup(app, EncryptedCookieStorage(secret_key)) for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) app['static_root_url'] = '/static' app.router.add_static('/static', 'static', name='static') logging.basicConfig(level=logging.DEBUG) #sll_certificate = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) #sll_certificate.load_cert_chain('domain_srv.crt', 'domain_srv.key') web.run_app(app)
def setup_session(app): if settings.DEBUG: secret_key = settings.SESSION_SECRET_KEY else: fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) aiohttp_session.setup(app, EncryptedCookieStorage(secret_key))
def init_app(settings) -> web.Application: """Initializes and starts the server""" app = web.Application() app['settings'] = settings aiohttp_session.setup(app, EncryptedCookieStorage(settings.SECRET_KEY)) app.router.add_routes(views.routes) app.router.add_routes(datasource_views.routes) app.router.add_routes(client_views.routes) app.router.add_routes(fmu_views.routes) app.router.add_routes(processor_views.routes) app.router.add_routes(blueprints_views.routes) cors = aiohttp_cors.setup(app, defaults={ '*': aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers='*', allow_headers='*', allow_methods='*' ) }) for route in list(app.router.routes()): cors.add(route) # TODO: these should be switched out with something that is not instance exclusive to enable horizontal scaling # Redis could for example be a viable alternative app['clients']: Dict[str, Client] = {} app['processors']: Dict[str, Processor] = {} app['subscribers'] = defaultdict(set) app['topics']: Dict[str, Dict] = {} app['topic_counter'] = 0 app.on_startup.append(start_background_tasks) app.on_cleanup.append(cleanup_background_tasks) return app
async def init(loop): app = web.Application() redis = await create_pool(('localhost', 6379)) setup(app, RedisStorage(redis, cookie_name="testmyid", max_age=3)) app.router.add_route('GET', '/', handler) srv = await loop.create_server(app.make_handler(), '0.0.0.0', 8084) return srv
def main(): options = {"swagger_ui": True} specification_dir = os.path.join(os.path.dirname(__file__), 'openapi') app = connexion.AioHttpApp(__name__, specification_dir=specification_dir, options=options, server_args=dict(middlewares=[db])) setup(app.app, EncryptedCookieStorage(Fernet.generate_key().decode())) db.init_app(app.app, config=dict(host=Const.DB_HOST, port=Const.DB_PORT, user=Const.DB_USER, password=Const.DB_PASSWORD, database=Const.DB_NAME)) app.add_api('openapi.yaml', arguments={'title': 'DSM Auth server'}, pythonic_params=True, pass_context_arg_name='request') app.app.cleanup_ctx.extend([get_public_key]) app.app.on_startup.append(create_tables) app.run(port=8080)
async def run_web_server(self, *, _action): # self = cls.init_from_file(**kwargs) # self.save_config() # self.log.info(f'{self.__class__.__name__} start up') app = web.Application( # middlewares=[ # self.middleware_auth, # self.middleware_index # ] ) app['device'] = self app['sessions'] = {} app['fast_storage'] = FastStorage() app['storage'] = Storage.connect(self) app.middlewares.append(self.middleware_index) setup(app, self.get_session_storage(app, 'AppSessionStorage')) app.middlewares.append(self.middleware_auth) drivers = find_drivers(log=self.log) self.set_param('/oic/mnt', 'drivers', drivers) self.build_i18n(drivers) self.add_routes(app) port = self.get_param('/oic/con', 'port', 80) # app.on_startup.append(self.start_background_tasks) # app.on_cleanup.append(self.cleanup_background_tasks) self.runner = web.AppRunner(app) await self.runner.setup() site = web.TCPSite(self.runner, None, port) await site.start() self.log.info( f'{self.__class__.__name__} started up http://localhost:{port}') return app
async def init_app(): app = web.Application() secret_key = base64.urlsafe_b64decode(BaseConfig.secret_key) setup(app, EncryptedCookieStorage(secret_key)) aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader(package_name='app', package_path='templates'), context_processors=[current_user_ctx_proccessor]) setup_routes(app) setup_static_routes(app) config = BaseConfig.load_config(args.config) app['config'] = config if args.reload: print() print('-------------------------------------------------') print("Start with code reload") aioreloader.start() app.on_startup.append(on_start) app.on_cleanup.append(on_shutdown) return app
def setup_session(app): from aiohttp_session import setup from aiohttp_session.cookie_storage import EncryptedCookieStorage from hashlib import sha256 session_secret_hash = sha256(app['conf'].session_secret.encode()).digest() storage = EncryptedCookieStorage(session_secret_hash) setup(app, storage)
def app(loop): """Default app fixture for tests.""" async def handler_remember(request): user_identity = request.match_info['user'] await auth.remember(request, user_identity) return web.Response(text='remember') @autz_required('admin') async def handler_admin(request): return web.Response(text='admin') @autz_required('guest') async def handler_guest(request): return web.Response(text='guest') application = web.Application(loop=loop) secret = b'01234567890abcdef' storage = aiohttp_session.SimpleCookieStorage() policy = auth.SessionTktAuthentication(secret, 15, cookie_name='auth') aiohttp_session.setup(application, storage) auth.setup(application, policy) autz_policy = CustomAutzPolicy(admin_user_identity='alex') autz.setup(application, autz_policy) application.router.add_get('/remember/{user}', handler_remember) application.router.add_get('/admin', handler_admin) application.router.add_get('/guest', handler_guest) yield application
def create_app(): fernet_key = fernet.Fernet.generate_key() SECRET_KEY = base64.urlsafe_b64decode(fernet_key) app = web.Application() # Инициализация БД engine = create_async_engine(DATABASE_URL, future=True, echo=True) app['DB ENGINE'] = engine app['DB SESSION'] = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) app['USERS'] = {} # Инициализируем пустым словарем app['ROOMS'] = { '1': [], '2': [], '3': [], } # Добавить комнаты ключом ROOMS setup(app, EncryptedCookieStorage(SECRET_KEY)) # Параметризацию для сокетов сюда - будут комнаты app.add_routes([ web.get('/ws/{room_id}', websocket_handler), web.post('/signin', sign_in), web.get('/rooms', room_list) ]) return app
def client(loop, aiohttp_client): logging.getLogger('connexion.operation').setLevel('ERROR') options = { "swagger_ui": True } specification_dir = os.path.join(os.path.dirname(__file__), '..', 'auth_server', 'openapi') app = connexion.AioHttpApp(__name__, specification_dir=specification_dir, options=options) app.app.cleanup_ctx.extend([ get_public_key ]) db.init_app(app.app, config=dict( host=Const.DB_HOST, port=Const.DB_PORT, user=Const.DB_USER, password=Const.DB_PASSWORD, database=Const.DB_NAME )) app.add_api('openapi.yaml', pythonic_params=True, pass_context_arg_name='request') fernet_key = fernet.Fernet.generate_key() Const.SESSION_KEY = fernet_key secret_key = base64.urlsafe_b64decode(fernet_key) setup(app.app, EncryptedCookieStorage(secret_key, cookie_name='auth_session')) return loop.run_until_complete(aiohttp_client(app.app))
async def main(): app = web.Application() app['websockets'] = [] redis_pool = await aioredis.create_pool('redis://localhost') storage = redis_storage.RedisStorage(redis_pool, max_age=600) app['redis_pool'] = redis_pool conn = await asyncpg.connect(user='******', database='chat', host='127.0.0.1') app['conn'] = conn async def dispose_redis_pool(app): try: await redis_pool.execute('FLUSHALL') except RuntimeError: # when no keys are registered in redis pass redis_pool.close() await redis_pool.wait_closed() await conn.execute('''TRUNCATE "log"''') await conn.close() setup(app, storage) app.on_cleanup.append(dispose_redis_pool) app.add_routes(routes) return app
def setup_sessions(app): #aoihttp_session expects the key to be decoded; but we're mounting a secret # that's automatically generated and made available to the app already # decoded hence for testing pass through the decoded data. secret_key = app['settings'].session_cookie_secret aiohttp_session.setup(app, EncryptedCookieStorage(secret_key))
def setup_session(app: web.Application): """ Inits and registers a session middleware in aiohttp.web.Application """ # secret key needed by EncryptedCookieStorage: is *bytes* key with length of *32* secret_key_bytes = app[APP_CONFIG_KEY]["session"]["secret_key"].encode( "utf-8") if len(secret_key_bytes) == 0: raise ValueError( "Empty %s.secret_key in config. Expected at least length 32") while len(secret_key_bytes) < 32: secret_key_bytes += secret_key_bytes # ------------------------------- # TODO: currently cfg and settings in place until former is dropped assert_valid_config(secret_key_bytes.decode("utf-8")) # nosec # ------------------------------- # EncryptedCookieStorage urlsafe_b64decode inside if passes bytes storage = EncryptedCookieStorage(secret_key=secret_key_bytes[:32], cookie_name="osparc.WEBAPI_SESSION") aiohttp_session.setup(app, storage)
def setup_session(self, key): if not key: key = base64.urlsafe_b64decode(Fernet.generate_key()) else: if isinstance(key, str): key = key.encode() setup(self.app, EncryptedCookieStorage(key))
async def init_app(): app = web.Application(debug=True, client_max_size=1024**2) secret_key = base64.urlsafe_b64decode(BaseConfig.secret_key) setup(app, EncryptedCookieStorage(secret_key)) aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader(package_name="app", package_path="templates"), context_processors=[current_user_ctx_proccessor]) setup_routes(app) setup_api_routes(app) setup_static_routes(app) config = BaseConfig.load_config(args.config) app['config'] = config db_pool = await init_db(app) log.debug(app['config']) if args.reload: print() print("------------------------------") print("Start with code reload") aioreloader.start() return app
async def init_app(is_test=False): """Initialize the application server.""" app = web.Application() setup(app=app, storage=EncryptedCookieStorage(secret_key=settings.SECRET_KEY)) app.middlewares.append(user_middleware) ssl_object = ssl.create_default_context( capath=r"sertificates/rds-combined-ca-bundle.pem") ssl_object.check_hostname = False ssl_object.verify_mode = ssl.CERT_NONE app["pool"] = await asyncpg.create_pool(dsn=settings.DSN, ssl=ssl_object) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader('tmpl'), ) app.add_routes(views.routes) # app.router.add_static('/static/', path='/static/', name='static') app.config = settings await models.setup(app) app.on_cleanup.append(models.close) return app
def create_app(): app = web.Application() settings = Settings() app.update( name='server', settings=settings, static='/static/', ) app.on_startup.append(startup) app.on_cleanup.append(cleanup) secret_key = base64.urlsafe_b64decode(settings.COOKIE_SECRET) aiohttp_session.setup(app, EncryptedCookieStorage(secret_key)) setup_routes(app) setup_middlewares(app) cors = aiohttp_cors.setup(app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers="*", allow_methods="*", allow_headers="*", max_age=3600) }) for route in app.router.routes(): cors.add(route) return app
def run(local_mode): app = web.Application() if local_mode: log.error('running in local mode with bogus cookie storage key') aiohttp_session.setup( app, aiohttp_session.cookie_storage.EncryptedCookieStorage( b'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', cookie_name=deploy_config.auth_session_cookie_name(), secure=True, httponly=True, domain=os.environ['HAIL_DOMAIN'], # 2592000s = 30d max_age=2592000, ), ) else: setup_aiohttp_session(app) setup_aiohttp_jinja2(app, 'website', jinja2.PackageLoader('website', 'pages'), jinja2.PackageLoader('website', 'docs')) setup_common_static_routes(routes) app.add_routes(routes) app.router.add_get("/metrics", server_stats) sass_compile('website') web.run_app( deploy_config.prefix_application(app, 'www'), host='0.0.0.0', port=5000, access_log_class=AccessLogger, ssl_context=None if local_mode else internal_server_ssl_context(), )
def init(): BASE_DIR = os.getcwd() # 项目路径 STATIC_DIR = os.path.join(BASE_DIR, 'static') # 静态文件路径 TEMPLATE_DIR = os.path.join(BASE_DIR, 'template') # 模版HTML路径 app = aiohttp.web.Application(middlewares=[middleware_allow]) # routes = gb.var['routes'] secret_key = 'This is the default secret_key' secret_key = hashlib.md5(base64.b64encode( secret_key.encode())).hexdigest().encode() setup(app, EncryptedCookieStorage(secret_key)) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(TEMPLATE_DIR), variable_start_string='{{{', variable_end_string='}}}', enable_async=True, context_processors=[aiohttp_jinja2.request_processor]) app.router.add_static('/static/', path=STATIC_DIR, name='static') app.router.add_routes(routes) aiohttp_jinja2.get_env(app).globals.update(gb.var['templateFuncClassDic']) print( f"\033[1;32;45m*** creat {len(gb.var['global_route'].routes)} route ***\033[0m" ) app.router.add_routes(gb.var['global_route'].routes) return app
async def init(loop): app = web.Application() setup(app, SimpleCookieStorage()) #setup(app, EncryptedCookieStorage(b'Thirty two length bytes key.')) app.router.add_route('GET', '/', handler) app.router.add_route('GET', '/ws', ws_handler) srv = await loop.create_server( app.make_handler(), '0.0.0.0', 8080) return srv
def run(self): event_loop = self.event_loop app = web.Application(loop=event_loop) #setup(app, SimpleCookieStorage()) setup(app, EncryptedCookieStorage(b'Thirty two length bytes key.')) app.router.add_route('GET', '/', self.root_handler) if self.secure: path = '/wss' else: path = '/ws' app.router.add_route('GET', path, self.ws_handler) app.router.add_route('GET', '/get_access', self.get_access) app.router.add_route('GET', '/login', self.authenticate) if self.secure: print("Using ssl cert: {}".format(self.cert)) sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext.load_cert_chain(self.cert) web.run_app(app, host=self.host_addr, port=self.port, ssl_context=sslcontext) else: web.run_app(app, host=self.host_addr, port=self.port)
import asyncio import time import base64 from cryptography import fernet from aiohttp import web from aiohttp_session import setup, get_session, session_middleware from aiohttp_session.cookie_storage import EncryptedCookieStorage @asyncio.coroutine def handler(request): session = yield from get_session(request) last_visit = session['last_visit'] if 'last_visit' in session else None session['last_visit'] = time.time() text = 'Last visited: {}'.format(last_visit) return web.Response(body=text.encode('utf-8')) app = web.Application() # secret_key must be 32 url-safe base64-encoded bytes fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) setup(app, EncryptedCookieStorage(secret_key)) app.router.add_route('GET', '/', handler) web.run_app(app)
return web.HTTPFound(cfg.oauth_redirect_path) return await fn(request, user, **kwargs) return wrapped @login_required async def index(request, user): text = ("<ul>" "<li>ID: %(id)s</li>" "<li>Username: %(username)s</li>" "<li>First, last name: %(first_name)s, %(last_name)s</li>" "<li>Gender: %(gender)s</li>" "<li>Email: %(email)s</li>" "<li>Link: %(link)s</li>" "<li>Picture: %(picture)s</li>" "<li>Country, city: %(country)s, %(city)s</li>" "</ul>") % user.__dict__ return web.Response(text=text, content_type='text/html') app = web.Application() app.router.add_get(cfg.oauth_redirect_path, oauth) app.router.add_get('/', index) if __name__ == '__main__': aiohttp_session.setup(app, EncryptedCookieStorage(cfg.secret_key)) web.run_app(app, port=8000)
def main(argv): logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)-8s %(message)s" ) for arg in argv: k, _, v = arg.partition("=") os.environ[k] = v logging.info("App starts...") app = web.Application() # Database from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine(os.environ["DB_DSN"], echo=False) db.Base.metadata.create_all(engine) session_factory = sessionmaker(bind=engine) @web.middleware async def add_db(request, handler): request["orm"] = session_factory() try: resp = await handler(request) finally: request["orm"].commit() request["orm"].close() return resp app.middlewares.append(add_db) populate_data(session_factory) # Templates aiohttp_mako.setup( app, directories=["./templates/"], input_encoding="utf-8", output_encoding="utf-8", default_filters=["unicode", "h"], ) # Sessions import base64 from cryptography import fernet from aiohttp_session import setup from aiohttp_session.cookie_storage import EncryptedCookieStorage if os.environ.get("SECRET"): fernet_key = os.environ["SECRET"].encode() else: fernet_key = fernet.Fernet.generate_key() print("SECRET=" + fernet_key.decode()) secret_key = base64.urlsafe_b64decode(fernet_key) setup(app, EncryptedCookieStorage(secret_key)) # Reloader try: import aiohttp_autoreload aiohttp_autoreload.start() except ImportError: pass # Setup Routes app.add_routes(routes) app.router.add_static("/static/", path="./static/", name="static") # Go! web.run_app(app, port=8000)
def setup_sessions(self): from aiohttp_session import setup from aiohttp_session.cookie_storage import EncryptedCookieStorage self.sessions = EncryptedCookieStorage(self.b64_key) setup(self.app, self.sessions) print('sessions setup')