async def init(): PROJECT_ROOT = Path(__file__).parent app = web.Application() aiohttp_debugtoolbar.setup(app, intercept_exc='debug') loader = jinja2.FileSystemLoader([str(TEMPLATE_DIR)]) aiohttp_jinja2.setup(app, loader=loader) routes = [ web.get('/', index, name='index'), web.get('/redirect', redirect, name='redirect'), web.get('/exception', exception, name='exception'), web.get('/jinja2_exc', jinja2_exception, name='jinja2_exception'), web.get('/ajax', ajax, name='ajax'), web.post('/ajax', ajax, name='ajax'), web.static('/static', PROJECT_ROOT / 'static'), ] if aiohttp_mako: mako_cfg = { 'input_encoding': 'utf-8', 'output_encoding': 'utf-8', 'default_filters': ['decode.utf8'], 'directories': [str(TEMPLATE_DIR)], } aiohttp_mako.setup(app, **mako_cfg) route = web.get('/mako_exc', mako_exception, name='mako_exception') routes.append(route) app.add_routes(routes) return app
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_template_not_found(loop): app = web.Application(loop=loop) aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) req = make_mocked_request('GET', '/', app=app) with pytest.raises(web.HTTPInternalServerError) as ctx: aiohttp_mako.render_template('template', req, {}) assert "Template 'template' not found" == ctx.value.text
def go(): app = web.Application(loop=loop) aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) app.router.add_route('GET', '/', func) req = make_request(app, 'GET', '/') with pytest.raises(web.HTTPInternalServerError) as ctx: yield from func(req) assert "Template 'template' not found" == ctx.value.text
def init(loop): app = web.Application(loop=loop, middlewares=[aiohttp_debugtoolbar.middleware]) aiohttp_debugtoolbar.setup(app, intercept_exc='debug') loader = jinja2.FileSystemLoader([templates]) aiohttp_jinja2.setup(app, loader=loader) if aiohttp_mako: aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], directories=[templates]) @aiohttp_mako.template('error.mako') def test_mako_exc(request): return {'title': 'Test Mako template exceptions'} app.router.add_route('GET', '/mako_exc', test_mako_exc, name='test_mako_exc') 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', '/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 init(loop): logging.basicConfig(level=logging.DEBUG) PROJECT_ROOT = Path(__file__).parent templates = PROJECT_ROOT / 'templates' app = web.Application(loop=loop) aiohttp_debugtoolbar.setup(app, intercept_exc='debug') loader = jinja2.FileSystemLoader([str(templates)]) aiohttp_jinja2.setup(app, loader=loader) if aiohttp_mako: aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], directories=[str(templates)]) @aiohttp_mako.template('error.mako') def test_mako_exc(request): return {'title': 'Test Mako template exceptions'} app.router.add_route('GET', '/mako_exc', test_mako_exc, name='test_mako_exc') # static view app.router.add_static('/static', 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', '/jinja2_exc', test_jinja2_exc, name='test_jinja2_exc') return app
def define_template_engine(app, settings): if settings.TEMPLATE_ENGINE.upper() == "MAKO": import aiohttp_mako aiohttp_mako.setup(app, directories=["webapi/templates_mako"]) app.template_seek_folders = [] # Do NOT Implemented yet _logger.info("Template Engine: 'MAKO'") elif settings.TEMPLATE_ENGINE.upper() == "JINJA2": import jinja2 import aiohttp_jinja2 seek_folders = settings.WEBSERVER_TEMPLATE_FOLDER app.template_seek_folders = seek_folders aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(seek_folders)) _logger.info("Template Engine: 'JINJA2'") else: _logger.info("Template Engine Not Defined") pass
def init(loop): # add aiohttp_debugtoolbar middleware to you application app = web.Application(loop=loop, middlewares=[aiohttp_debugtoolbar .toolbar_middleware_factory]) # install aiohttp_debugtoolbar aiohttp_debugtoolbar.setup(app) # install mako templates lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) 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> """ lookup.put_string('index.html', template) 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
async def init(): global interval global ws init_data() app = web.Application() # 한글 주석들이 파싱하다가 에러가 나버리는 바람에 샘플대로 encoding 옵션을 다시 모두 넣어줬습니다 # directories 부분을 지정해주면 샘플과 달리 파일을 직접 언급해서 가져올수 있습니다 lookup = aiohttp_mako.setup(app,directories=['html'], input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) #lookup = aiohttp_mako.setup(app, directories=['.']) #lookup.put_string('index.html', '''<h2>${name}</h2>''') app.router.add_static('/static', 'static') app.router.add_get('/', handle) app.router.add_get('/update/{server}/{cur_user}/{itemset}', update) #app.router.add_get('/update/{server}/{cur_user}/{itemset}/{proto}', update) app.router.add_get('/update_indiv/{num}/{server}/{cur_user}/{cur_itemset}/{itemname}', update_indiv) app.router.add_get('/create_itemset/{cur_user}/{setname}', create_itemset) app.router.add_get('/delete_itemset/{cur_user}/{setname}', delete_itemset) # 웹소켓 핸들러도 get을 통해 정의해줘야합니다 ws = app.router.add_get('/ws', ws_handle) loop = asyncio.get_event_loop() loop.create_task(main_proc(interval)) return app
async def test_request_processor(aiohttp_client): app = web.Application() lookup = aiohttp_mako.setup( app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], context_processors=[aiohttp_mako.request_processor] ) tplt = "<html><body><h1>${head}</h1>path=${request.path}</body></html>" lookup.put_string('tplt.html', tplt) @aiohttp_mako.template('tplt.html') async def func(request): return {'head': 'HEAD'} app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '<html><body><h1>HEAD</h1>path=/</body></html>' == txt
def go(): app = web.Application(loop=loop) lookup1 = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) lookup2 = aiohttp_mako.get_lookup(app) assert lookup1 is lookup2 assert isinstance(lookup2, TemplateLookup)
async def init(loop): app = web.Application(loop=loop) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) template = """<html><body><h1>${head}</h1>${text}</body></html>""" lookup.put_string('index.html', template) app.router.add_route('GET', '/', func) return app
def create_app(context_processors): app = web.Application() lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], context_processors=context_processors) tplt = "<html><body><h1>${head}</h1>${text}</body></html>" lookup.put_string('tplt.html', tplt) return app
def app(loop): app = web.Application(loop=loop) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) tplt = "<html><body><h1>${head}</h1>${text}</body></html>" lookup.put_string('tplt.html', tplt) return app
async def init(loop): app = web.Application(loop=loop) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) lookup.put_string('index.html', Path("index.html").read_text()) lookup.put_string('notes.html', Path("notes.html").read_text()) app.router.add_route('GET', '/', addNoteRequestHandlerGET) app.router.add_route('POST', '/', addNoteRequestHandlerPOST) app.router.add_route('GET', '/notes', listMyNotes) return app
def init(loop): app = web.Application(loop=loop) lookup = aiohttp_mako.setup(app, input_encoding="utf-8", output_encoding="utf-8", default_filters=["decode.utf8"]) template = """<html><body><h1>${head}</h1>${text}</body></html>""" lookup.put_string("index.html", template) app.router.add_route("GET", "/", func) handler = app.make_handler() srv = yield from loop.create_server(handler, "127.0.0.1", 8080) print("Server started at http://127.0.0.1:8080") return srv, handler
async def init(loop): logging.basicConfig(level=logging.DEBUG) PROJECT_ROOT = Path(__file__).parent templates = PROJECT_ROOT / 'templates' app = web.Application(loop=loop) aiohttp_debugtoolbar.setup(app, intercept_exc='debug') loader = jinja2.FileSystemLoader([str(templates)]) aiohttp_jinja2.setup(app, loader=loader) if aiohttp_mako: aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], directories=[str(templates)]) @aiohttp_mako.template('error.mako') def test_mako_exc(request): return {'title': 'Test Mako template exceptions'} app.router.add_route('GET', '/mako_exc', test_mako_exc, name='test_mako_exc') # static view app.router.add_static('/static', 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', '/jinja2_exc', test_jinja2_exc, name='test_jinja2_exc') return app
def init(): app = web.Application() lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) template = open(Configs.INDEX_PATH).read() lookup.put_string("index.html", template) app.router.add_routes(routes) return app
def make_app(bot): app = web.Application() app['state'] = State.idle app['action_index'] = 0 app['clients'] = set() app['bot'] = bot app['position'] = 0, 0 app['pen_up'] = None bot.enable_motors(1) bot.servo_setup(config.PEN_DOWN_POSITION, config.PEN_UP_POSITION, config.SERVO_SPEED, config.SERVO_SPEED) app['pen_up_delay'], app['pen_down_delay'] = \ planning.calculate_pen_delays(config.PEN_UP_POSITION, config.PEN_DOWN_POSITION, config.SERVO_SPEED) # This will initialize the server state. filename = 'line.svg' with open(os.path.join(examples_dir, filename)) as f: doc = f.read() app['job'] = job = plotting.process_upload(app, doc, filename) app['estimated_time'] = job.duration().total_seconds() app['consumed_time'] = 0 aiohttp_mako.setup(app, directories=[template_dir], input_encoding='utf-8', output_encoding='utf-8', imports=['from markupsafe import escape'], default_filters=['escape']) app.router.add_route('GET', '/', views.index) app.router.add_route('GET', '/api', handlers.client_handler) app.router.add_static('/static', static_dir) return app
def init(): app = web.Application() #aiohttp_mako.setup(app, directories='html-test') lookup = aiohttp_mako.setup(app, directories=['html-test'], input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) app.router.add_get('/', handle) app.router.add_static('/static', 'static') return app
async def init(loop): app = web.Application(loop=loop) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) template = """<html><body><h1>${head}</h1>${text}</body></html>""" lookup.put_string('index.html', template) app.router.add_route('GET', '/', func) handler = app.make_handler() srv = await loop.create_server(handler, '127.0.0.1', 8080) print("Server started at http://127.0.0.1:8080") return srv, handler
def create(*, debug=False, **kw): nonlocal app, app_handler, srv app = web.Application(loop=loop) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) tplt = "<html><body><h1>${head}</h1>${text}</body></html>" lookup.put_string('tplt.html', tplt) app_handler = app.make_handler(debug=debug, keep_alive_on=False) port = unused_port srv = yield from loop.create_server(app_handler, '127.0.0.1', port) url = "http://127.0.0.1:{}/".format(port) return app, url
def _setup_app(self, handler, **kw): app = web.Application(loop=self.loop, middlewares=[toolbar_middleware_factory]) tbsetup(app, **kw) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) tplt = "<html><body><h1>${head}</h1>${text}</body></html>" lookup.put_string('tplt.html', tplt) app.router.add_route('GET', '/', handler) srv = yield from self.loop.create_server( app.make_handler(), '127.0.0.1', self.port) self.addCleanup(srv.close) return app
def go(): app = web.Application(loop=loop) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) tplt = "<html><body><h1>${head}</h1>${text}</body></html>" lookup.put_string('tmpl.html', tplt) app.router.add_route('GET', '/', func) req = make_request(app, 'GET', '/') with pytest.raises(web.HTTPInternalServerError) as ctx: yield from func(req) assert "context should be mapping, not" \ " <class 'str'>" == ctx.value.text
async def server(robot: RobotV2): app = web.Application() app['robot'] = robot # ops = OperationsV1() ops = DummyOperations() ops.register(app) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) with open("page.mako") as f: template = f.read() lookup.put_string('index.html', template) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, '0.0.0.0', 8080) await site.start() while True: await asyncio.sleep(1)
async def test_template_not_mapping(): @aiohttp_mako.template('tmpl.html') async def func(request): return 'data' app = web.Application() lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) tplt = "<html><body><h1>${head}</h1>${text}</body></html>" lookup.put_string('tmpl.html', tplt) app.router.add_route('GET', '/', func) req = make_mocked_request('GET', '/', app=app) with pytest.raises(web.HTTPInternalServerError) as ctx: await func(req) assert "context should be mapping, not" \ " <class 'str'>" == ctx.value.text
def start_web(conf: config.Config, slots: cgroup.SlotManager) -> None: async def shutdown(): print("letting runner do cleanup") await runner.cleanup() def sigusr1_handler() -> None: print("Received SIGUSR1, shutting down...") loop.create_task(shutdown()) async def stop_loop(app) -> None: print("shutdown") loop.stop() async def start_runner(runner, conf: config.Config): await runner.setup() site: Optional[Union[web.TCPSite, web.UnixSite, web.SockSite]] = None if conf.port is not None: print(f"Starting HTTP server on localhost:{conf.port}") site = web.TCPSite(runner, 'localhost', conf.port) elif conf.socket is not None: print(f"Starting UNIX socket server on {conf.socket}") site = web.UnixSite(runner, conf.socket) elif conf.socket_fd is not None: print(f"Starting UNIX socket server on FD {conf.socket_fd}") sock = socket.socket(fileno=conf.socket_fd) site = web.SockSite(runner, sock) assert site is not None, "Invalid config, no listening address" return await site.start() app = web.Application() templates_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates") aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], directories=[templates_dir]) eval_sem = asyncio.BoundedSemaphore(conf.max_workers) handle_is = get_eval_handler(eval_sem, conf, slots, InterfaceMode.IS | InterfaceMode.Priviledged) app.router.add_get("/is", handle_is) app.router.add_post("/is", handle_is) handle_hint = get_eval_handler(eval_sem, conf, slots, InterfaceMode.Null) app.router.add_get("/hint", handle_hint) app.router.add_post("/hint", handle_hint) handle_internal = get_eval_handler(eval_sem, conf, slots, InterfaceMode.Priviledged) app.router.add_get("/internal", handle_internal) app.router.add_post("/internal", handle_internal) handle_admin = get_handle_admin(conf) app.router.add_get("/admin/{user}/{course_id}/", handle_admin) app.router.add_post("/admin/{user}/{course_id}/", handle_admin) app.router.add_get("/admin/{user}/{course_id}/{page}", handle_admin) app.router.add_post("/admin/{user}{course_id}/{page}", handle_admin) runner = web.AppRunner(app, handle_signals=True) app.on_cleanup.append(stop_loop) loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGUSR1, sigusr1_handler) try: loop.run_until_complete(start_runner(runner, conf)) except Exception: print("ERROR starting server", file=sys.stderr) traceback.print_exc() sys.exit(1) print("started, loaded following configuration:") conf.dump(sys.stdout) try: loop.run_forever() finally: loop.close()
async def hello(request): print(request.query) # access_log.info('abcc...........') return web.json_response({'status': 0, 'data': {'a': 1, 'b': 1}}) @routes.post('/') async def phello(request): data = await request.post() print(data) print('aaabb') return web.json_response({'status': 0, 'data': {'a': 2, 'b': 2}}) @aiohttp_mako.template('index.html') @routes.get('/mako') async def mako_test(request): return {'aa': '22'} app = web.Application(debug=True) app.add_routes(routes) # for rsrc in app.router.resources(): # print(rsrc) lookup = aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) lookup.put_string('index.html', '''<html><body><h1>${aa}</h1>${aa}</body></html>''') web.run_app(app)
async def init(app): global interval global ws #app = web.Application() # 한글 주석들이 파싱하다가 에러가 나버리는 바람에 샘플대로 encoding 옵션을 다시 모두 넣어줬습니다 # directories 부분을 지정해주면 샘플과 달리 파일을 직접 언급해서 가져올수 있습니다 lookup = aiohttp_mako.setup(app, directories=['html'], input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) #lookup = aiohttp_mako.setup(app, directories=['.']) #lookup.put_string('index.html', '''<h2>${name}</h2>''') #app.router.add_static('/static', 'static') app.router.add_get('/', handle) app.router.add_get('/u/{user_code}/{itemset_code:.*}', user) app.router.add_get('/u/{user_code}', user) app.router.add_get('/update/{server}/{cur_user}/{itemset}/{dummy}', update) app.router.add_get('/update/{server}/{cur_user}/{itemset}', update) app.router.add_get('/rq_servertime/{server}/{dummy}', rq_servertime) app.router.add_get('/rq_servertime/{server}', rq_servertime) app.router.add_get('/rq_itemset/{cur_user}/{itemset}/{dummy}', rq_itemset) app.router.add_get('/rq_itemsets/{cur_user}/{dummy}', rq_itemsets) app.router.add_get('/rq_item/{num}/{server}/{item}/{dummy}', rq_item) #app.router.add_get('/rq_item/{cur_user}/{num}/{server}/{fullstr}/{dummy}', rq_item) app.router.add_get( '/update_indiv/{num}/{server}/{cur_user}/{cur_itemset}/{itemname}/{fullstr}/{dummy}', update_indiv) #app.router.add_get('/update_indiv/{num}/{server}/{cur_user}/{cur_itemset}/{itemname}/{dummy}', #update_indiv) app.router.add_get('/create_user/{user_name}', create_user) app.router.add_get('/login/{user_name}', login) app.router.add_get('/create_itemset/{cur_user}/{setname}', create_itemset) app.router.add_get('/delete_itemset/{cur_user}/{setname}', delete_itemset) # 웹소켓 핸들러도 get을 통해 정의해줘야합니다 ws = app.router.add_get('/ws', ws_handle) # db에 바로 접속해 놓습니다 engine = await create_engine(user='******', database='auction_db', host='localhost', password='******') app['db'] = engine #별도의 db proc을 돌리므로 뺍니다. 불필요한 업데이트가 초반 두번 일어나는 결과를 불러옵니다 ''' loop = asyncio.get_event_loop() loop.create_task(main_proc(interval)) ''' loop = asyncio.get_event_loop() app['loop'] = loop loop.create_task(init_proc(app['db'])) app['redis'] = await aioredis.create_redis('redis://localhost', loop=loop) # 서버리스트를 가져오고 (X 최초아이템 셋도 가져옵니다) #init_data() return app
async def test(): async def json_context_processor(request): return {'json': lambda value: json.dumps(value)} lookup = aiohttp_mako.setup(app, context_processors=[ aiohttp_session_flash.context_processor, json_context_processor, ]) lookup.put_string('index.html', '${json(get_flashed_messages())}') async def save(request): flash(request, "Hello") return web.Response(body=b'OK') async def save_redirect(request): flash(request, "Redirect") raise web.HTTPFound('/') async def save_array(request): flash(request, ["This", "works", "too"]) return web.Response(body=b'OK') async def show(request): return web.Response(body=json.dumps(pop_flash(request)).encode('utf-8')) @aiohttp_mako.template('index.html') async def show_context_processor(request): return {} app.router.add_route('GET', '/save', save) app.router.add_route('GET', '/save_redirect', save_redirect) app.router.add_route('GET', '/save_array', save_array) app.router.add_route('GET', '/show', show) app.router.add_route('GET', '/show_context_processor', show_context_processor) handler = app.make_handler() port = find_unused_port() srv = await app.loop.create_server(handler, '127.0.0.1', port) url = "http://127.0.0.1:{}".format(port) async with aiohttp.ClientSession() as session: async with session.get(url+'/save') as resp: assert resp.status == 200 session.cookie_jar.update_cookies(resp.cookies) # something in the response prevents this from happening automatically. async with session.get(url+'/save_redirect', allow_redirects=False) as resp: assert resp.status == 302 session.cookie_jar.update_cookies(resp.cookies) async with session.get(url+'/save_array') as resp: assert resp.status == 200 session.cookie_jar.update_cookies(resp.cookies) async with session.get(url+'/show') as resp: assert resp.status == 200 assert (await resp.text()) == '["Hello", "Redirect", ["This", "works", "too"]]' session.cookie_jar.update_cookies(resp.cookies) async with session.get(url+'/show') as resp: assert resp.status == 200 assert (await resp.text()) == '[]' session.cookie_jar.update_cookies(resp.cookies) async with session.get(url+'/save') as resp: assert resp.status == 200 session.cookie_jar.update_cookies(resp.cookies) async with session.get(url+'/show_context_processor') as resp: assert resp.status == 200 assert (await resp.text()) == '["Hello"]' session.cookie_jar.update_cookies(resp.cookies)
def setup(app, **kw): config = {} config.update(default_settings) config.update(kw) APP_ROOT = os.path.dirname(os.path.abspath(__file__)) app[APP_KEY] = {} templates_app = os.path.join(APP_ROOT, 'templates') templates_panels = os.path.join(APP_ROOT, 'panels/templates') app[APP_KEY]['settings'] = config aiohttp_mako.setup(app, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8'], directories=[templates_app, templates_panels], app_key=TEMPLATE_KEY) static_location = os.path.join(APP_ROOT, 'static') exc_handlers = ExceptionDebugView() app.router.add_static('/_debugtoolbar/static', static_location, name=STATIC_ROUTE_NAME) app.router.add_route('GET', '/_debugtoolbar/source', exc_handlers.source, name='debugtoolbar.source') app.router.add_route('GET', '/_debugtoolbar/execute', exc_handlers.execute, name='debugtoolbar.execute') # app.router.add_route('GET', '/_debugtoolbar/console', # exc_handlers.console, # name='debugtoolbar.console') app.router.add_route('GET', '/_debugtoolbar/exception', exc_handlers.exception, name='debugtoolbar.exception') # TODO: fix when sql will be ported # app.router.add_route('GET', '_debugtoolbar/sqlalchemy/sql_select', # name='debugtoolbar.sql_select') # app.router.add_route('GET', '_debugtoolbar/sqlalchemy/sql_explain', # name='debugtoolbar.sql_explain') app.router.add_route('GET', '/_debugtoolbar/sse', views.sse, name='debugtoolbar.sse') app.router.add_route('GET', '/_debugtoolbar/{request_id}', views.request_view, name='debugtoolbar.request') app.router.add_route('GET', '/_debugtoolbar', views.request_view, name='debugtoolbar.main') app.router.add_route('GET', '/_debugtoolbar', views.request_view, name='debugtoolbar') def settings_opt(name): return app[APP_KEY]['settings'][name] max_request_history = settings_opt('max_request_history') app[APP_KEY]['request_history'] = ToolbarStorage(max_request_history) app[APP_KEY]['exc_history'] = ExceptionHistory() app[APP_KEY]['pdtb_token'] = hexlify(os.urandom(10)) intercept_exc = settings_opt('intercept_exc') if intercept_exc: app[APP_KEY]['exc_history'].eval_exc = intercept_exc == 'debug'
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)