async def init(loop): global app, dbpool redis = await aioredis.create_pool(('localhost', 6379)) storage = redis_storage.RedisStorage(redis) session_middleware1 = session_middleware(storage) #dbpool = await my_create_pool(dsn) dbpool = await aiopg.create_pool(dsn) app = web.Application(middlewares=[session_middleware1]) #app = web.Application(middlewares=[session_middleware( # EncryptedCookieStorage(b'Thirty two length bytes key.'))]) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(path('templates'))) # app.router.add_route('GET', '/test/ws/', ws_test) app.router.add_route('GET', '/admin/', admin) app.router.add_route('GET', '/admin/{host}/', admin) app.router.add_route('GET', '/admin/{host}/{nickname}/', chat_page_admin) app.router.add_route('POST', '/admin/{host}/{nickname}/', new_msg) app.router.add_route('GET', '/admin/{host}/{nickname}/ws/', websocket_handler) app.router.add_route('GET', '/', hello) app.router.add_route('POST', '/', hello) app.router.add_route('GET', '/{host}/', chat_page, name='chat_page') app.router.add_route('POST', '/{host}/', new_msg) app.router.add_route('GET', '/{host}/ws/', websocket_handler) srv = await loop.create_server( app.make_handler(), '0.0.0.0', 8080) return srv
def go(): app = web.Application(loop=self.loop, middlewares=( aiohttp_jinja2.context_processors_middleware, )) aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': 'foo: {{ foo }}, bar: {{ bar }}, path: {{ request.path }}'})) app['aiohttp_jinja2_context_processors'] = ( aiohttp_jinja2.request_processor, asyncio.coroutine( lambda request: {'foo': 1, 'bar': 'should be overwriten'}), ) app.router.add_route('GET', '/', func) port = self.find_unused_port() handler = app.make_handler() srv = yield from self.loop.create_server( handler, '127.0.0.1', port) url = "http://127.0.0.1:{}/".format(port) resp = yield from aiohttp.request('GET', url, loop=self.loop) self.assertEqual(200, resp.status) txt = yield from resp.text() self.assertEqual('foo: 1, bar: 2, path: /', txt) yield from handler.finish_connections() srv.close() self.addCleanup(srv.close)
def init(loop): adminMainController = AdminMainController() engine = yield from create_engine(**config['db']) with (yield from engine) as connection: adminUserController = AdminUserController( adminMainController, users, connection) redis = yield from aioredis.create_pool(('localhost', 6379)) storage = RedisStorage(redis) app = web.Application(middlewares=[session_middleware(storage)]) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) app.router.add_route('GET', '/', main_page_view) app.router.add_route('GET', '/admin', adminMainController.get) app.router.add_route( 'GET', '/admin/{table}', adminMainController.get_table) app.router.add_route( 'POST', '/admin/{table}', adminMainController.create_record) app.router.add_static('/dist', 'dist') server = yield from loop.create_server(app.make_handler(), '127.0.0.1', 8080) return server
async def init(loop): # setup application and extensions app = web.Application(loop=loop) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT))) # load config from yaml file conf = load_config(str(PROJ_ROOT / 'config' / 'dev.yml')) # create connection to the database pg = await init_postgres(conf['postgres'], loop) async def close_pg(app): pg.close() await pg.wait_closed() # setup dummy auth and identity ident_policy = DummyTokenIdentityPolicy() auth_policy = DummyAuthPolicy(username="******", password="******") aiohttp_security.setup(app, ident_policy, auth_policy) # setup admin views admin_config = str(PROJ_ROOT / 'static' / 'js') setup_admin(app, pg, admin_config) app.on_cleanup.append(close_pg) # setup views and routes handler = SiteHandler(pg) setup_routes(app, handler, PROJ_ROOT) host, port = conf['host'], conf['port'] return app, host, port
def _set_loaders(self): loader = jinja2.ChoiceLoader(self.loaders) aiohttp_jinja2.setup(self.app, loader=loader, extensions=['jinja2_time.TimeExtension'], context_processors=[self.agent_processor, aiohttp_jinja2.request_processor] )
def init(loop): app = web.Application(middlewares=[ session_middleware(EncryptedCookieStorage(conf.SECRET)), auth.auth_middleware, ]) aiohttp_jinja2.setup( app, context_processors=[context.static, aiohttp_jinja2.request_processor], loader=jinja2.FileSystemLoader(conf.relative('templates')) ) yield from get_storage().init_storage() if conf.DEBUG: app.router.add_static(conf.STATIC_URL, conf.STATIC_PATH) for _ in urls.urls: url, view, methods = (_ + (['GET', ], ))[:3] for method in methods: app.router.add_route(method, url, view) 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
def init(loop): u"""Создание сервера.""" app = web.Application(loop=loop) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(os.path.join(CWD, 'web/html')) ) app.router.add_route('GET', '/ws', wshandler) app.router.add_route('POST', '/hook', hook) app.router.add_route('GET', '/', index) app.router.add_route('GET', '/dashboard', dashboard) app.router.add_route('GET', '/new', new_project) app.router.add_route('GET', '/edit/{project:.*}', edit_project) app.router.add_route('GET', '/view/{project:.*}', view_project) app.router.add_route('GET', '/view_report/{report_path:.*}', view_report) app.router.add_route('GET', '/view_log/{log_path:.*}', view_log) # app.router.add_route('GET', '/static/{path:.*}', static_handle) app.router.add_route('GET', '/run/{project:.*}', run_project) # app.router.add_route('POST', '/slack', slack) app.router.add_static('/static', os.path.join(CWD, 'web')) app.router.add_static('/logs', os.path.join(CWD, 'logs')) app.router.add_static('/artefacts', os.path.join(CWD, 'artefacts')) srv = yield from loop.create_server(app.make_handler(), '0.0.0.0', PORT) print("Server started at http://0.0.0.0:%s" % PORT) return srv
def init_gunicorn(): global mc middlewares = [] middlewares.append(db_handler()) if settings.debug: middlewares.append( session_middleware(SimpleCookieStorage()) ) else: middlewares.append( session_middleware(EncryptedCookieStorage(settings.session_key)) ) app = web.Application( middlewares=middlewares ) aiohttp_jinja2.setup(app, loader=jinja2.FunctionLoader ( load_templ ) ) # Memcache init app.mc = aiomcache.Client( settings.memcache['addr'], settings.memcache['port']) # Mongo init db_connect(app) union_routes( os.path.join(settings.tao_path, 'libs' ) ) union_routes( os.path.join(settings.root_path, 'apps') ) union_routes( os.path.join(settings.root_path ), p=True ) for res in routes: name = res[3] if name is None: name = '{}:{}'.format(res[0], res[2]) app.router.add_route( res[0], res[1], res[2], name=name) path = os.path.join(settings.root_path, 'static') app.router.add_static('/static/', path, name='static') return app
async def make_app(): app = web.Application() app.router.add_get('/api/v1/data', handler) app.router.add_get('/', handler) endpoint = az.create_endpoint('service_a', ipv4=host, port=port) tracer = await az.create(zipkin_address, endpoint, sample_rate=1.0) trace_config = az.make_trace_config(tracer) session = aiohttp.ClientSession(trace_configs=[trace_config]) app['session'] = session async def close_session(app): await app['session'].close() app.on_cleanup.append(close_session) az.setup(app, tracer) TEMPLATES_ROOT = pathlib.Path(__file__).parent / 'templates' aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT)) ) return app
def init(loop): app = web.Application(loop=loop) app.router.add_route('GET', '/', root) app.router.add_route('GET', '/sm/{arkadasno}', sendMessage) app.router.add_route('GET', '/df/{arkadasno}', deleteFriend) app.router.add_route('GET', '/lf/{toxid}', listFiles) app.router.add_route('GET', '/dugumler', dugumler) app.router.add_route('POST', '/dps_baglan', dps_baglan) app.router.add_route('GET', '/guncelle', guncelle) app.router.add_route('GET', '/dps', dps) app.router.add_route('GET', '/mesajlasma', mesajlasma) app.router.add_static("/static",'./static') aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('./templates')) srv = yield from loop.create_server(app.make_handler(),'127.0.0.1', 7001) print("Web sunucusu http://127.0.0.1:7001 başlatıldı.") init_callbacks(tox) # bootstrap print ("bootstrap dugumlerine baglanıyor...") for data in node_generator(): tox.bootstrap(*data) tox.self_set_name("milis-toxia-"+sonek) tox.self_set_status_message("Milis Toxia") asyncio.Task(toxloop()) asyncio.Task(paysun()) return srv
def get_app(): app = aiohttp.web.Application() app['api-url'] = os.environ['ICW_API'] app['google-analytics-tracking-id'] = os.environ.get('GOOGLE_ANALYTICS_TRACKING_ID') app['api-session'] = aiohttp.ClientSession() app['static-url'] = '/static/' app.router.add_route('*', '/', handlers.IndexHandler()) app.router.add_route('*', '/incident', handlers.AccidentListHandler()) app.router.add_route('*', '/incident/{accident_id}', handlers.AccidentDetailHandler()) app.router.add_route('*', '/about-data', handlers.AboutDataHandler()) app.router.add_static(app['static-url'], os.path.join(os.path.dirname(__file__), 'static')) negotiation.setup(app) aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('icw.web', 'templates'), context_processors=[asyncio.coroutine(lambda request: { 'static_url': app['static-url'], 'api_url': app['api-url'], 'google_analytics_tracking_id': app['google-analytics-tracking-id'] })]) return app
def init(loop): # add aiohttp_debugtoolbar middleware to you application app = web.Application(loop=loop) # install aiohttp_debugtoolbar aiohttp_debugtoolbar.setup(app) template = """ <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ text }}</h1> <p> <a href="{{ app.router['exc_example'].url() }}"> Exception example</a> </p> </body> </html> """ # install jinja2 templates loader = jinja2.DictLoader({'index.html': template}) aiohttp_jinja2.setup(app, loader=loader) # init routes for index page, and page with error app.router.add_route('GET', '/', basic_handler, name='index') app.router.add_route('GET', '/exc', exception_handler, name='exc_example') handler = app.make_handler() srv = yield from loop.create_server(handler, '127.0.0.1', 9000) print("Server started at http://127.0.0.1:9000") return srv, handler
def create_app(loop, config, debug=False): app = Application(loop=loop, middlewares=[db_factory, session_middleware_factory]) @asyncio.coroutine def static_processor(request): return {'static_url': config['http']['static_url']} aiohttp_jinja2.setup( app, context_processors=[static_processor, aiohttp_jinja2.request_processor], loader=aiohttp_jinja2.jinja2.FileSystemLoader(os.path.join(BASE_DIR, 'templates')) ) app['sockets'] = [] app['tw_consumer_key'] = os.environ.get('CONSUMER_KEY') app['tw_consumer_secret'] = os.environ.get('CONSUMER_SECRET') app['secret_key'] = os.environ.get('SECRET_KEY') app['config'] = config app.router.add_route('GET', '/', index_handler) app.router.add_route('GET', '/signin', signin_handler) app.router.add_route('GET', '/callback', callback_handler) app.router.add_route('GET', '/tweets', ws_handler) if debug: app.router.add_route('GET', '/static/{a}', static_handler) app.router.add_route('GET', '/static/{a}/{b}', static_handler) app.router.add_route('GET', '/static/{a}/{b}/{c}', static_handler) return app
def create_app(): servers, buttons = read_config() app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader( os.path.join(CURR, './templates'))) @aiohttp_jinja2.template('main.html') async def main(request): return {"buttons": buttons} async def send(request): data = request.match_info if request.method == "POST": data = await request.post() server = servers[data['server']] assert data['button'] in buttons[data['server']][data['remote']] return json.dumps(subprocess.check_call(["irsend", "-a", server, data['method'], data['remote'], data['button']])) async def put(request): post = await request.post() current_cfg = json.load(open(os.path.expanduser('~/.mremote.conf'))) with post['config'] as file_: server_name = request.match_info['server_name'] ip, _ = request.transport.get_extra_info('peername') current_cfg[0].update({server_name: ip}) current_cfg[1].update({server_name: lirc_cfg(file_)}) with open(os.path.expanduser('~/.mremote.conf'), 'w') as cfg: json.dump(current_cfg, cfg) app.router.add_route('*', '/m', send) app.router.add_route('*', '/m/{server}/{remote}/{button}/{method}', send) app.router.add_route('PUT', '/{server_name}', put) app.router.add_route('GET', '/', main) return app
def main(): """OOI运行主函数。 :return: none """ # 解析命令行参数 args = parser.parse_args() host = args.host port = args.port # 初始化事件循环 loop = asyncio.get_event_loop() # 初始化请求处理器 api = APIHandler() frontend = FrontEndHandler() service = ServiceHandler() # 定义会话中间件 middlewares = [session_middleware(EncryptedCookieStorage(config.secret_key)), ] # 初始化应用 app = aiohttp.web.Application(middlewares=middlewares, loop=loop) # 定义Jinja2模板位置 aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(config.template_dir)) # 给应用添加路由 app.router.add_route('GET', '/', frontend.form) app.router.add_route('POST', '/', frontend.login) app.router.add_route('GET', '/kancolle', frontend.normal) app.router.add_route('GET', '/kcv', frontend.kcv) app.router.add_route('GET', '/flash', frontend.flash) app.router.add_route('GET', '/poi', frontend.poi) app.router.add_route('GET', '/connector', frontend.connector) app.router.add_route('GET', '/logout', frontend.logout) app.router.add_route('GET', '/kcsapi/{action:.+}', api.api) app.router.add_route('POST', '/kcsapi/{action:.+}', api.api) app.router.add_route('GET', '/kcs/resources/image/world/{server:.+}_{size:[lst]}.png', api.world_image) app.router.add_route('POST', '/service/osapi', service.get_osapi) app.router.add_route('POST', '/service/flash', service.get_flash) app.router.add_static('/static', config.static_dir) app.router.add_static('/kcs', config.kcs_dir) app.router.add_static('/_kcs', config.kcs_dir) app_handlers = app.make_handler() # 启动OOI服务器 server = loop.run_until_complete(loop.create_server(app_handlers, host, port)) print('OOI serving on http://%s:%d' % server.sockets[0].getsockname()) try: loop.run_forever() except KeyboardInterrupt: pass finally: loop.run_until_complete(app_handlers.finish_connections(1.0)) server.close() loop.run_until_complete(server.wait_closed()) loop.run_until_complete(app.finish()) loop.close()
async def test_render_bare_funcs_deprecated(aiohttp_client): def wrapper(func): async def wrapped(request): with pytest.warns(DeprecationWarning, match='Bare functions are deprecated'): return await func(request) return wrapped @wrapper @aiohttp_jinja2.template('tmpl.jinja2') def func(request): return {'text': 'OK'} app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': '{{text}}'})) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert 'OK' == txt
async def test_meth(aiohttp_client): class Handler: @aiohttp_jinja2.template('tmpl.jinja2') async def meth(self, request): return {'head': 'HEAD', 'text': 'text'} template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>' handler = Handler() app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', handler.meth) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '<html><body><h1>HEAD</h1>text</body></html>' == txt
def init_app(self): from nautilus.api.endpoints import template_dir as api_template_dir from nautilus.auth import template_dir as auth_template_dir # the secret key secret_key = 'NERbTdtQl7IrBM9kx1PDjJXiyZhWWBZ9E7q2B3U7KVE=' # create a web application instance self.app = aiohttp.web.Application( middlewares=[ session_middleware( EncryptedCookieStorage(secret_key, secure=True, domain='*') ) ] ) # add the template loader aiohttp_jinja2.setup(self.app, loader=jinja2.ChoiceLoader([ jinja2.FileSystemLoader(api_template_dir), jinja2.FileSystemLoader(auth_template_dir) ]) ) # TODO: # debug mode # attach the ioloop to the application self.loop = asyncio.get_event_loop() # attach the service to the loop self.loop.service = self
async def init(loop): middle = [ session_middleware(EncryptedCookieStorage(SECRET_KEY)), authorize, db_handler, ] if DEBUG: middle.append(aiohttp_debugtoolbar.middleware) app = web.Application(loop=loop, middlewares= middle ) app['websockets'] = [] handler = app.make_handler() if DEBUG: aiohttp_debugtoolbar.setup(app) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) # route part for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) app.router.add_static('/static', 'static', name='static') # end route part # db connect app.client = ma.AsyncIOMotorClient(MONGO_HOST) app.db = app.client[MONGO_DB_NAME] # end db connect app.on_shutdown.append(on_shutdown) serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app
def init(aio_loop, mysql_pool, port=8080, config=None, sslcontext=None): app = web.Application(loop=aio_loop, middlewares=[authentication_middleware]) app['current_cost_service'] = CurrentCostDatabaseReader(mysql_pool, full_hours_start=time(7), full_hours_stop=time(23)) app['redis_cmd_publisher'] = RedisPublisher((yield from create_redis_pool()), RFXCOM_KEY_CMD) app['switch_service'] = SwichService(mysql_pool) app['config'] = config app.router.add_static(prefix='/static', path=os.path.dirname(__file__) + '/static') aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/templates')) app.router.add_route('GET', '/livedata/power', stream) app.router.add_route('GET', '/', home) app.router.add_route('GET', '/menu/piscine', piscine) app.router.add_route('GET', '/menu/apropos', apropos) app.router.add_route('GET', '/menu/conso_electrique', conso_electrique) app.router.add_route('GET', '/menu/commandes', commandes) app.router.add_route('GET', '/menu/commandes/execute/{code_device}/{value}', command_execute) app.router.add_route('POST', '/menu/commandes/add', commandes_add) app.router.add_route('GET', '/power/history', power_history) app.router.add_route('GET', '/power/day/{iso_date}', power_by_day) app.router.add_route('GET', '/power/costs/{since}', power_costs) listening_ip = '0.0.0.0' srv = yield from aio_loop.create_server(app.make_handler(), listening_ip, port, ssl=sslcontext) logger.info("Domopyc web server started at http://%s:%s" % (listening_ip, port)) return srv
def init(loop, argv): ap = argparse.ArgumentParser() commandline.standard_argparse_options(ap, default_config='./config/polls.yaml') # # define your command-line arguments here # options = ap.parse_args(argv) config = commandline.config_from_options(options, TRAFARET) # setup application and extensions app = web.Application(loop=loop) # load config from yaml file in current dir app['config'] = config # setup Jinja2 template renderer aiohttp_jinja2.setup( app, loader=jinja2.PackageLoader('aiohttpdemo_polls', 'templates')) # create connection to the database app.on_startup.append(init_pg) # shutdown db connection on exit app.on_cleanup.append(close_pg) # setup views and routes setup_routes(app) setup_middlewares(app) return app
def __init__(self, *args, debug=False, **kwargs): debug = debug or os.environ.get('DEBUG', 'False') == 'True' super(SeoDemoApplication, self).__init__(*args, debug=debug, **kwargs) aiohttp_jinja2.setup(self, loader=jinja2.FileSystemLoader('templates')) self.load_config() self.load_routes()
def setup_jinja2(self): import aiohttp_jinja2 import jinja2 templates = os.path.join(self.path, 'templates') loader = jinja2.FileSystemLoader(templates) aiohttp_jinja2.setup(self.app, loader=loader) print('jinja2 setup')
async def init(loop): # load config from yaml file conf = load_config(str(PROJ_ROOT / 'config' / 'dev.yml')) # setup application and extensions app = web.Application(loop=loop) pg = await setup_pg(app, conf, loop) # init modules aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT))) # setup dummy auth and identity ident_policy = DummyTokenIdentityPolicy() auth_policy = DummyAuthPolicy(username="******", password="******") aiohttp_security.setup(app, ident_policy, auth_policy) admin_config = str(PROJ_ROOT / 'static' / 'js') setup_admin(app, pg, admin_config) # setup views and routes handler = SiteHandler(pg) add_route = app.router.add_route add_route('GET', '/', handler.index) app.router.add_static('/static', path=str(PROJ_ROOT / 'static')) host, port = conf['host'], conf['port'] return app, host, port
def create_app(self, loop): app = web.Application(loop=loop) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('tanner/web/templates')) app.on_shutdown.append(self.on_shutdown) self.setup_routes(app) return app
def _create_app_with_template(self, template, func): """ Helper method that creates application with single handler that process request to root '/' with any http method and returns response for rendered `template` """ app = web.Application(loop=self.loop) aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', func) port = self.find_unused_port() handler = app.make_handler() srv = yield from self.loop.create_server( handler, '127.0.0.1', port) url = 'http://127.0.0.1:{}/'.format(port) resp = yield from aiohttp.request('GET', url, loop=self.loop) yield from handler.finish_connections() srv.close() self.addCleanup(srv.close) return resp
def main(): """ Scrapy pull request: configure_logging() should accept a config argument Note: scrapy.utils.log.TopLevelFormatter is cool need to access Scrapy loggger's handler and replace the filter with a new TopLevelFormatter with more names: e.g. ['scrapy', 'scrapybox', 'aiohttp'] """ configure_logging(settings) logger.info('Scrapybox server starting') # formatter = logging.Formatter(fmt=settings.get('LOG_FORMAT'), # datefmt=settings.get('LOG_DATEFORMAT')) # handler = logging.StreamHandler() # handler.setFormatter(formatter) # handler.setLevel(settings.get('LOG_LEVEL')) # logging.root.addHandler(handler) twisted.internet.reactor.run() logger.info('Twisted reactor running') app = aiohttp.web.Application( loop=asyncio.get_event_loop(), # middlewares=[aiohttp_debugtoolbar.toolbar_middleware_factory] ) # aiohttp_debugtoolbar.setup(app) # http://127.0.0.1:8080/_debugtoolbar aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(user_path)) app.on_shutdown.append(on_shutdown) app['static_path'] = user_path scrapybox.server.routes.add(app) logger.info('Aiohttp server starting') aiohttp.web.run_app(app)
def __init__(self, *args, **kwargs): # NOTE we use HTTPPermanentRedirect (308) because # clients sometimes turn POST requests into GET requests # on 301, 302, or 303 # see https://tools.ietf.org/html/rfc7538 trailing_slash_redirect = normalize_path_middleware( append_slash=True, redirect_class=HTTPPermanentRedirect ) self.subapp = web.Application( middlewares=[ oauth_problem_middleware, trailing_slash_redirect ] ) AbstractAPI.__init__(self, *args, **kwargs) aiohttp_jinja2.setup( self.subapp, loader=jinja2.FileSystemLoader( str(self.options.openapi_console_ui_from_dir) ) ) middlewares = self.options.as_dict().get('middlewares', []) self.subapp.middlewares.extend(middlewares)
def init(loop): app = web.Application(loop=loop, middlewares=[toolbar_middleware_factory]) aiohttp_debugtoolbar.setup(app, intercept_exc='debug') aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], directories=[templates]) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(templates)) # static view app.router.add_static('/static', os.path.join(PROJECT_ROOT, 'static')) app.router.add_route('GET', '/redirect', test_redirect, name='test_redirect') app.router.add_route('GET', '/', test_page, name='test_page') app.router.add_route('GET', '/exc', exc, name='test_exc') # ajax handlers app.router.add_route('GET', '/ajax', test_ajax, name='test_ajax') app.router.add_route('GET', '/call_ajax', call_ajax, name='call_ajax') # templates error handlers app.router.add_route('GET', '/mako_exc', test_mako_exc, name='test_mako_exc') app.router.add_route('GET', '/jinja2_exc', test_jinja2_exc, name='test_jinja2_exc') handler = app.make_handler() srv = yield from loop.create_server(handler, '127.0.0.1', 9000) log.debug("Server started at http://127.0.0.1:9000") return srv, handler
def test_context_processors(create_server, loop): @aiohttp_jinja2.template('tmpl.jinja2') @asyncio.coroutine def func(request): return {'bar': 2} app, url = yield from create_server( middlewares=[ aiohttp_jinja2.context_processors_middleware]) aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': 'foo: {{ foo }}, bar: {{ bar }}, path: {{ request.path }}'})) app['aiohttp_jinja2_context_processors'] = ( aiohttp_jinja2.request_processor, asyncio.coroutine( lambda request: {'foo': 1, 'bar': 'should be overwriten'}), ) app.router.add_route('GET', '/', func) resp = yield from aiohttp.request('GET', url, loop=loop) assert 200 == resp.status txt = yield from resp.text() assert 'foo: 1, bar: 2, path: /' == txt
async def test_render_template_custom_status(aiohttp_client): async def func(request): return aiohttp_jinja2.render_template('tmpl.jinja2', request, { 'head': 'HEAD', 'text': 'text' }, status=404) template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({'tmpl.jinja2': template})) app.router.add_route('*', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 404 == resp.status txt = await resp.text() assert '<html><body><h1>HEAD</h1>text</body></html>' == txt
async def init_webserver(self, port): app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates/')) routes = [ web.get('/', self.main_page), web.post('/transact', self.transact_web), web.post('/create_obj', self.create_obj_web), ] app.add_routes(routes) app.router.add_static("/sample_img", 'templates/images', name="img") app.router.add_static("/scrolling", 'templates/js', name="scl") app.router.add_static("/css", 'templates/css', name="css") app.router.add_static("/jquery_js", 'templates/vendor/jquery', name="jqjs") app.router.add_static("/boot_js", 'templates/vendor/bootstrap/js', name="boot_js") app.router.add_static("/es_js", 'templates/vendor/jquery-easing/', name="esa_js") runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, 'localhost', port) await site.start()
def init_aiohttp_app(loop, logger=None, client_max_size=None, config=None): if logger: app = web.Application(loop=loop, logger=logger) else: app = web.Application(loop=loop) # load config from yaml file in current dir app.config = config # setup Jinja2 template renderer aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('webapp', 'templates')) # database app.on_startup.append(init_db) app.on_cleanup.append(close_db) app.connection = defaultdict(set) # setup views and routes setup_routes(app) setup_middlewares(app) return app
def test_meth(loop, test_client): class Handler: @aiohttp_jinja2.template('tmpl.jinja2') @asyncio.coroutine def meth(self, request): return {'head': 'HEAD', 'text': 'text'} template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>' handler = Handler() app = web.Application(loop=loop) aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({'tmpl.jinja2': template})) app.router.add_route('*', '/', handler.meth) client = yield from test_client(app) resp = yield from client.get('/') assert 200 == resp.status txt = yield from resp.text() assert '<html><body><h1>HEAD</h1>text</body></html>' == txt
def init(): loop = asyncio.get_event_loop() # setup application and extensions app = web.Application(loop=loop) # load config from yaml file in current dir conf = load_config(str(pathlib.Path('.') / 'config' / 'polls.yaml')) app['config'] = conf # setup Jinja2 template renderer aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('aiohttpdemo_polls', 'templates')) # create connection to the database app.on_startup.append(init_pg) # shutdown db connection on exit app.on_cleanup.append(close_pg) # setup views and routes setup_routes(app) setup_middlewares(app) return app
async def init_app(config): app = web.Application() app['config'] = config db = await init_db(app) fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) db_url = construct_db_url(CONFIG['postgres']) engine = create_engine(db_url) create_tables(engine) setup_session( app, EncryptedCookieStorage(secret_key) ) aiohttp_jinja2.setup( app, loader=jinja2.PackageLoader('url_shorter','templates'), context_processors=[current_user_ctx_processor], filters={'datetimeformat': datetimeformat} ) setup_security( app, SessionIdentityPolicy(), DBAuthorizationPolicy(db) ) setup_routes(app) app.on_startup.append(init_db) app.on_cleanup.append(close_pg) return app
def __init__(self, scheduler, storage, udp_port, cron=None, user=None, hash_key=None): self.scheduler = scheduler self.storage = storage self.udp_port = udp_port self.cron = cron self.user = user self.hash_key = hash_key self.app = web.Application() aiohttp_jinja2.setup(self.app, loader=jinja2.PackageLoader('dcron', 'templates')) self.app.router.add_static('/static/', path=self.root / 'static', name='static') self.app.add_routes([ web.get('/', self.get), web.get('/list_nodes', self.get_nodes), web.get('/cron_in_sync', self.cron_in_sync), web.get('/status', self.status), web.get('/list_jobs', self.get_jobs), web.get('/jobs', self.jobs), web.post('/add_job', self.add_job), web.post('/remove_job', self.remove_job), web.post('/get_job_log', self.get_job_log), web.post('/kill_job', self.kill_job), web.post('/run_job', self.run_job), web.post('/toggle_job', self.toggle_job), web.get('/export', self.export_data), web.post('/import', self.import_data), web.post('/re-balance', self.re_balance) ])
async def create_app(): config = read_configuration_file() db_pool = await attach_db(config) app = web.Application(middlewares=[error_middleware, babel_middleware]) app["config"] = config app["db-pool"] = db_pool app["mailer"] = MassMailer() # beware of order ! setup_session(app) setup_security( app, SessionIdentityPolicy(), DBAuthorizationPolicy(db_pool) ) app.middlewares.append(aiohttp_session_flash.middleware) template_dir = op.join(op.dirname(op.abspath(__file__)), "templates") aiohttp_jinja2.setup( app, loader=FileSystemLoader(template_dir), context_processors=( aiohttp_session_flash.context_processor, authorized_userid_context_processor ) ) jinja2_env = aiohttp_jinja2.get_env(app) jinja2_env.globals['_'] = _ setup_routes(app) app.on_cleanup.append(cleanup) return app
def bootstrap(loop=None, env=None): if not loop: loop = asyncio.get_event_loop() app = web.Application(loop=loop) app.loop.set_task_factory(aiotask_context.task_factory) aiohttp_jinja2.setup(app, loader=FileSystemLoader( path.join(path.dirname(__file__), './templates'))) config = load_config(env) secrets = load_secrets(config) EnvironmentVars.init(config, secrets) init_logging(config.get('LOG_CONFIG')) load_handlers(app) # todo I hate hate hate this # it's not necessary for most systems, but was originally devised for a system that had no # external access available (either DB or servers) # normally you could just run migrations from a jumpbox/laptop schema = open( path.join(path.dirname(__file__), '../resources/db/schema.sql')).read() try: logging.info('migrating') database = Environment.database() loop.run_until_complete(asyncio.gather(database.migrate(schema))) except psycopg2.Error as e: print('failed to migrate') print(str(e)) print('error code: ' + str(e.pgcode)) print('error: ' + str(e.pgerror)) return app
def __init__(self, *args: List, **kwargs: dict): self._name = type(self).__name__ super(AppConfig, self).__init__(*args, **kwargs) self.path = APP_DIR.joinpath(self._name) # configure templating: # TODO: using Notify Logic about aiohttp jinja if self.template: template_dir = os.path.join(self.path, self.template) # template_dir = self.path.resolve().joinpath(self.template) aiohttp_jinja2.setup(self.app, loader=jinja2.FileSystemLoader(template_dir)) # set the setup_routes self.setup_routes() # setup cors: # self.setup_cors(self.cors) if self.enable_swagger is True: from aiohttp_swagger import setup_swagger setup_swagger(self.app, api_base_url=f'/{self._name}', title=f'{self._name} API', api_version=self.__version__, description=self.app_description, swagger_url=f"/api/v1/doc", ui_version=3)
async def init(loop): # setup application and extensions app = web.Application(loop=loop) aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT))) # load config from yaml file conf = load_config(str(PROJ_ROOT / 'config' / 'polls.yaml')) # create connection to the database pg = await init_postgres(conf['postgres'], loop) async def close_pg(app): pg.close() await pg.wait_closed() app.on_cleanup.append(close_pg) # setup views and routes handler = SiteHandler(pg) setup_routes(app, handler, PROJ_ROOT) setup_middlewares(app) host, port = conf['host'], conf['port'] return app, host, port
def main(): host = sys.argv[1] if len(sys.argv) > 1 else "0.0.0.0" sslcontext = None loop = asyncio.get_event_loop() server = web.Application(loop=loop) template_loader = jinja2.FileSystemLoader("/cega") aiohttp_jinja2.setup(server, loader=template_loader) # Registering the routes server.router.add_get('/', index, name='root') server.router.add_get('/lega/v1/legas/users/{identifier}', user, name='user') server.router.add_get('/pgp/{id}', pgp_pbk, name='pgp') web.run_app(server, host=host, port=80, shutdown_timeout=0, ssl_context=sslcontext)
async def init_app(config): app = web.Application() app['config'] = config setup_routes(app) db_pool = await init_db(app) redis_pool = await setup_redis(app) setup_session(app, RedisStorage(redis_pool)) aiohttp_jinja2.setup( app, loader=jinja2.PackageLoader('for_templates', 'templates'), context_processors=[current_user_ctx_processor], ) setup_security(app, SessionIdentityPolicy(), DBAuthorizationPolicy(db_pool)) log.debug(app['config']) return app
def create_app(*args): app = web.Application() app.add_routes([ web.get('/', home), web.get(r'/repos/detail/{repo_slug}', repo_detail, name='repo_detail'), web.get('/traffic-data/', get_traffic_chart_data_json), web.get('/combined-data/', get_combined_chart_data_json), web.static('/static', STATIC_ROOT, name='static'), ]) app.on_startup.append(create_dbstore) j_env = aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader( os.path.join(BASE_PATH, 'templates'))) templatetags.setup(j_env) return app
def test_url(create_server, loop): @aiohttp_jinja2.template('tmpl.jinja2') @asyncio.coroutine def index(request): return {} @asyncio.coroutine def other(request): return app, url = yield from create_server() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': "{{ url('other', parts={'name': 'John_Doe'})}}" })) app.router.add_route('GET', '/', index) app.router.add_route('GET', '/user/{name}', other, name='other') resp = yield from aiohttp.request('GET', url, loop=loop) assert 200 == resp.status txt = yield from resp.text() assert '/user/John_Doe' == txt
def create_app(): app = web.Application() settings = Settings() app.update(name='{{ name }}', settings=settings) # {% if template_engine.is_jinja %} app['static_root_url'] = '/' jinja2_loader = jinja2.FileSystemLoader(str(THIS_DIR / 'templates')) aiohttp_jinja2.setup(app, loader=jinja2_loader) # {% 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
async def main(): app = web.Application() aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader('templates')) # 将模板添加到搜索路径 app.router.add_static('/static/', path=os.path.join( os.path.dirname(os.path.abspath(__file__)), 'static')) # 将静态文件添加到搜索路径 app.router.add_route('GET', '/', index) app.router.add_route('GET', '/startMonitor', start_monitor) app.router.add_route('GET', '/getMonitor/{host}', get_monitor) app.router.add_route('GET', '/Visualize', visualize) app.router.add_route('GET', '/getPortAndDisk/{host}', get_port_disk) app.router.add_route('POST', '/Register', registers) app.router.add_route('POST', '/runMonitor', run_monitor) app.router.add_route('POST', '/plotMonitor', plot_monitor) app.router.add_route('POST', '/Notification', notice) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, cfg.getServer('host'), cfg.getServer('port')) await site.start()
async def test_jinja_filters(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def index(request): return {} def add_2(value): return value + 2 app = web.Application() aiohttp_jinja2.setup( app, loader=jinja2.DictLoader({'tmpl.jinja2': "{{ 5|add_2 }}"}), filters={'add_2': add_2}, enable_async=True, ) app.router.add_route('GET', '/', index) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '7' == txt
def test_render_template(loop, test_client): @asyncio.coroutine def func(request): return aiohttp_jinja2.render_template( 'tmpl.jinja2', request, {'head': 'HEAD', 'text': 'text'}) template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>' app = web.Application(loop=loop) aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', func) client = yield from test_client(app) resp = yield from client.get('/') assert 200 == resp.status txt = yield from resp.text() assert '<html><body><h1>HEAD</h1>text</body></html>' == txt
async def create_app(config): app = web.Application() app["config"] = config aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader("cardsstore", "templates")) setup_routes(app) # secret_key must be 32 url-safe base64-encoded bytes fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) storage = EncryptedCookieStorage(secret_key, cookie_name="API_SESSION") setup_session(app, storage) policy = SessionIdentityPolicy() app["db"] = await aioredis.create_pool(config["database_uri"]) setup_security(app, policy, DictionaryAuthorizationPolicy(app["db"])) app.on_startup.append(on_start) app.on_cleanup.append(on_shutdown) return app
async def create_app(): """ Create web application and manage connection to redis :return: instance of application """ app = web.Application() jinja_env = aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader('templates')) for route in routes: app.router.add_route(**route) startup_tasks = [startup] app.on_startup.extend(startup_tasks) app.on_cleanup.append(cleanup) aiojobs_setup(app) return app
async def start(self, app): env = aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'templates')), extensions=[HamlishExtension]) env.hamlish_file_extensions = ('.haml', ) env.hamlish_mode = 'debug' env.hamlish_enable_div_shortcut = True app.router.add_static('/static', os.path.join(os.path.dirname(__file__), 'static'), name='static') env.filters['static'] = lambda x: app.router.named_resources()[ 'static'].url_for(filename=x) env.filters['datetime'] = format_dt
def get_app(): app = web.Application() # secret_key must be 32 url-safe base64-encoded bytes fernet_key = Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) setup_session(app, cookie_storage.EncryptedCookieStorage(secret_key)) setup_routes(app) setup_orm(app) env = aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('chestnut', 'templates')) env.filters['sysconfig'] = lambda _: '' env.globals['url'] = url_for app.middlewares.append(right_check) return app
def make_app(data_dir: str): app = web.Application() ctx = app[APP_CTX_KEY] = ApplicationContext(data_dir=data_dir) jinja2_env = aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(here / 'templates'), context_processors=[aiohttp_jinja2.request_processor], ) jinja2_env.globals.update({ 'ctx': ctx, 'COURSE_MENU_ITEMS': COURSE_MENU_ITEMS, 'fa': fa, 'fix_img_src': fix_img_src, 'sort_by_id': sort_by_id, }) app.add_routes([ # lists web.view('/', IndexView), web.view(r'/course/{id:\d+}', CourseView), web.view(r'/course/{id:\d+}/announcement', AnnouncementListView), web.view(r'/course/{id:\d+}/material', MaterialListView), web.view(r'/course/{id:\d+}/discussion', DiscussionListView), web.view(r'/course/{id:\d+}/homework', HomeworkListView), # single item list web.view(r'/course/{id:\d+}/score', ScoreView), web.view(r'/course/{id:\d+}/grouplist', GroupView), # single item web.view(r'/announcement/{id:\d+}', AnnouncementView), web.view(r'/material/{id:\d+}', MaterialView), web.view(r'/discussion/{id:\d+}', DiscussionView), web.view(r'/homework/{id:\d+}', HomeworkView), web.view(r'/homework/{id:\d+}/submissions', SubmissionListView), web.view(r'/submittedhomework/{id:\d+}', SubmissionRedirectView), web.view(r'/homework/{hid:\d+}/submissions/{id:\d+}', SubmissionView), # downloads web.view(r'/attachment/{id:\d+}', AttachmentView), web.view(r'/video/{id:\d+}', VideoView), # redirects web.get('/sys/read_attach.php', read_attach_php), web.view('/course.php', CoursePHP), web.get('/sys/res/icon/{filename}', icon_redirect), # misc web.get('/robots.txt', robots_txt), ]) return app
def startup(setup_mode): # Entry point. Return an awaitable to be run. # encrypted cookies for session logic from aiohttp_session.nacl_storage import NaClCookieStorage from aiohttp_session import session_middleware todays_key = os.urandom(32) sml = session_middleware(NaClCookieStorage(todays_key, cookie_name='X')) # create app: order of middlewares matters app = web.Application(middlewares=[sml, auth_everything]) app.add_routes(routes) app.router.add_static('/static', './static') # hack to obfuscate our identity a little # - from <https://w3techs.com/technologies/details/ws-nginx/1> 23% market share import aiohttp.web_response as ht ht.SERVER_SOFTWARE = 'nginx/1.14.1' j_env = aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'), filters=extra_filters(app)) j_env.globals.update(default_context()) j_env.policies['json.dumps_function'] = json_dumps my_url = f"http://localhost:{settings.PORT_NUMBER}" + ('/setup' if setup_mode else '') logging.info(f"Web server at: {my_url}") # meh; kinda annoying. if 0: def popup(): try: # see <https://github.com/jupyter/notebook/issues/3746#issuecomment-444957821> # if this doesn't happen on MacOS from webbrowser import open as open_browser open_browser(my_url) except: logging.error("Unable to pop browser open", exc_info=1) asyncio.get_running_loop().call_later(3, popup) from aiohttp.abc import AbstractAccessLogger class AccessLogger(AbstractAccessLogger): def log(self, request, response, time): self.logger.info(f'{response.status} <= {request.method} {request.path}') return web._run_app(app, port=settings.PORT_NUMBER, print=None, access_log_class=AccessLogger)
def init_jinja2(app, **kw): logging.info("Init jinja2 ...") options = dict(autoescape=kw.get('autoescape', True), block_start_string=kw.get('block_start_string', '{%'), block_end_string=kw.get('block_end_string', '%}'), variable_start_string=kw.get('variable_start_string', '{{'), variable_end_string=kw.get('variable_end_string', '}}'), auto_reload=kw.get('auto_reload', True)) path = kw.get('path', None) if path is None: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') env = aiohttp_jinja2.setup(app, loader=FileSystemLoader(path), **options) filters = kw.get('filters', None) if filters is not None: for name, func in filters.items(): env.filters[name] = func app['__templating__'] = env
def __init__(self, app: Application, *, loader: Optional[BaseLoader] = None, context_processors: Iterable[Callable[[Request], Dict[str, Any]]] = (), filters: Optional[Iterable[Callable[..., str]]] = None, extensions: Optional[Union[Iterable[str], Iterable[Extension]]] = []): self.filters = filters self.env = setup(app=app, loader=loader, context_processors=context_processors, filters=filters, extensions=extensions, trim_blocks=True, lstrip_blocks=True)
def startup(app, config, locales): templates_path = app['config']['templates_path'] env = aiohttp_jinja2.setup( app, context_processors=[ computed_processor(debug=app.debug), config_processor(config=app['config']), locales_processor(locales_config=config.locales_config, locales=locales), fonts_processor(locales_config=config.locales_config, fonts_config=config.fonts_config), ], default_helpers=False, filters={ 'squash': _squash, }, loader=jinja2.FileSystemLoader(templates_path), auto_reload=False, bytecode_cache=jinja2.FileSystemBytecodeCache())
def setup_email(app: web.Application, debug: bool = False): # ---------------------------------------------- # TODO: temporary, just to check compatibility between # trafaret and pydantic schemas assert_valid_config(app) # --------------------------------------------- tmpl_dir = resources.get_path("templates") if not tmpl_dir.exists(): log.error("Cannot find email templates in '%s'", tmpl_dir) return False env = aiohttp_jinja2.setup( app, loader=jinja_app_loader.Loader(), # jinja2.FileSystemLoader(tmpl_dir) auto_reload=debug, ) return env
def init_jinja2(): jinja2_env = aiohttp_jinja2.setup(app, autoescape=True, loader=jinja2.FileSystemLoader( os.path.join( os.path.dirname(__file__), 'views'))) def url_for(route, filename): parameters = {} if "static" == route and app["config"]["DEBUG"]: parameters["hash"] = static_file_hash( os.path.join(static_folder, filename)) return app.router[route].url(filename=filename, query=parameters) def static_file_hash(filename): return int(os.stat(filename).st_mtime) jinja2_env.globals['url_for'] = url_for