async def get_app(debug=False): middlewares = [] if debug: middlewares += [toolbar_middleware_factory] app = web.Application(middlewares=middlewares) if debug: aiohttp_debugtoolbar.setup(app, intercept_redirects=False) router = app.router router.add_routes(routes) router.add_static('/static', 'static') aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'), context_processors=[static_processor]) app['waiters'] = defaultdict(BList) # Close all websockets form broadcast list async def close_websockets(app): for channel in app['waiters'].values(): for waiter in channel: await waiter['ws'].close(code=1000, message="Server shutdown") app.on_shutdown.append(close_websockets) return app
async def init(loop, config, debug=False): setup_structlog(config) log = structlog.get_logger() app = SenzaApp(config=config, loop=loop, logger=log, middlewares=[structlog_middleware]) await app.setup() listen_address = app.config['server']['listen_address'].strip() if debug: import aiohttp_debugtoolbar aiohttp_debugtoolbar.setup(app, hosts=[listen_address]) log.info('Debug toolbar available at /_debugtoolbar') listen_port = app.config['server']['listen_port'] srv = await loop.create_server(app.make_handler(), listen_address, listen_port) for socket in srv.sockets: log.info('Server started at %s', socket.getsockname()) return srv
def create_app() -> web.Application: import aiohttp_debugtoolbar app = init_app() aiohttp_debugtoolbar.setup(app, check_host=False) return app
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
async def init(loop): logger.info('Start truck chat') middle = [ session_middleware(EncryptedCookieStorage(settings.SECRET_KEY)), ] # add debug if settings.DEBUG: middle.append(aiohttp_debugtoolbar.middleware) app = web.Application(loop=loop, middlewares=middle) # init app common storages app['websockets'] = [] app['chats_websockets'] = {} if settings.DEBUG: aiohttp_debugtoolbar.setup(app) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) # init routes for route in routes: logger.debug('Add route %s', route) app.router.add_route(route[0], route[1], route[2], name=route[3]) # set static app.router.add_static('/static', 'static', name='static') # init db and redis db_engine = await init_postgres_engine(loop) app.db_engine = db_engine app.redis = await init_redis(loop) app_handler = app.make_handler(access_log=logger) srv = await loop.create_server(app_handler, settings.SITE_HOST, settings.SITE_PORT) return srv, app_handler
async def init(loop): logging.basicConfig(level=logging.DEBUG) # maybe later add authorize middleware app = web.Application(loop=loop,middlewares=[ session_middleware(EncryptedCookieStorage(SECRET_KEY)), db_handler, ],debug=True) aiohttp_debugtoolbar.setup(app) handler = app.make_handler() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) # route part app.router.add_static('/static', 'static', name='static') app.router.add_static('/node_modules', 'node_modules', name='static_dist') for api_route in API_ROUTES: app.router.add_route(api_route[0], api_route[1], api_route[2], name=api_route[3]) for route in routes: app.router.add_route(route[0], route[1], route[2], name=route[3]) # end route part # db connect app.client = ma.AsyncIOMotorClient(MONGO_HOST) app.db = app.client[MONGO_DB_NAME] # end db connect serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app
async def init(loop): app = web.Application(loop=loop, middlewares=[ session_middleware(EncryptedCookieStorage(SECRET_KEY)), authorize, db_handler, aiohttp_debugtoolbar.middleware, ]) app['websockets'] = defaultdict(list) handler = app.make_handler() if DEBUG: aiohttp_debugtoolbar.setup(app, intercept_redirects=False) 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.db = await init_db( host=MYSQL_HOST, db=MYSQL_DB_NAME, user=MYSQL_USER, password=MYSQL_PASSWORD, loop=loop ) # end db connect app.on_shutdown.append(on_shutdown) serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app
async def init(loop): middle = [ error_middleware, auth_middleware, ] if settings.DEBUG: middle.append(aiohttp_debugtoolbar.middleware) app = web.Application(loop=loop, middlewares=middle, debug=settings.DEBUG) app['websockets'] = [] if settings.DEBUG: aiohttp_debugtoolbar.setup(app) # Set up routes routes.setup(app) # Use content negotiation middleware to render JSON responses negotiation.setup(app) await setup_models(app) app.on_shutdown.append(on_shutdown) setup_scheduler(app) handler = app.make_handler() server = loop.create_server(handler, settings.HOST, settings.PORT) return server, handler, 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_for() }}"> 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 setup(self): if self.settings.DEBUG: aiohttp_debugtoolbar.setup(self) # configure application router self.router_config.link_routes()
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 main(): syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_DAEMON) syslog.syslog('Web server controlling daemon starting...') app = web.Application(middlewares=[aiohttp_debugtoolbar.middleware], ) # app = web.Application() try: with open(flag_state, 'r') as f: command = f.readline(); finally: if command not in ['disable', 'enable']: command = 'enable' app['checked'], app['disabled'] = newstate[command] app['status'] = get_daemon_status(daemon) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) aiohttp_debugtoolbar.setup(app, intercept_redirects=False) app.add_routes([web.get('/', render_page), web.get('/{command}', handle_command) ]) web.run_app(app, host='localhost', port=8080) syslog.syslog('Web server controlling daemon finish')
async def create_app(): """ Prepare application """ redis_pool = await aioredis.create_pool(settings.REDIS_CON) middlewares = [ session_middleware(RedisStorage(redis_pool)), request_user_middleware ] if settings.DEBUG: middlewares.append(aiohttp_debugtoolbar.middleware) # init application app = web.Application(middlewares=middlewares) app.redis_pool = redis_pool app.ws_list = {} jinja_env = aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(settings.TEMPLATE_DIR), context_processors=[aiohttp_jinja2.request_processor], ) jinja_env.globals.update(tags) if settings.DEBUG: aiohttp_debugtoolbar.setup(app, intercept_redirects=False) # db conn database.init(**settings.DATABASE) app.database = database app.database.set_allow_sync(False) app.objects = peewee_async.Manager(app.database) # make routes from urls import routes for route in routes: app.router.add_route(**route) app.router.add_static('/static', settings.STATIC_DIR, name='static') app.logger = logger return app
def modify_main_app(app, config: Config): """ Modify the app we're serving to make development easier, eg. * modify responses to add the livereload snippet * set ``static_root_url`` on the app * setup the debug toolbar """ app._debug = True dft_logger.debug('livereload enabled: %s', '✓' if config.livereload else '✖') if config.livereload: livereload_snippet = LIVE_RELOAD_SNIPPET % config.aux_port async def on_prepare(request, response): if not request.path.startswith( '/_debugtoolbar') and 'text/html' in response.content_type: if getattr(response, 'body', None): response.body += livereload_snippet app.on_response_prepare.append(on_prepare) static_url = 'http://localhost:{}/{}'.format(config.aux_port, config.static_url.strip('/')) app['static_root_url'] = static_url dft_logger.debug('app attribute static_root_url="%s" set', static_url) if config.debug_toolbar: aiohttp_debugtoolbar.setup(app, intercept_redirects=False)
async 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_for() }}"> 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') return app
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
def setup_server(): app = web.Application() aiohttp_debugtoolbar.setup(app) # CORS Implementation # `aiohttp_cors.setup` returns `aiohttp_cors.CorsConfig` instance. # The `cors` instance will store CORS configuration for the application. cors = aiohttp_cors.setup( app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*", # allow_methods="*", ) }) resource = cors.add(app.router.add_resource("/upload/")) cors.add(resource.add_route( "POST", post_file)) # Add handler for POST request on ./upload # Routers app.router.add_get("/", index) app.router.add_get("/ViewPage", index) app.router.add_get("/geometry", get_geometry) app.router.add_get("/trajectory", get_trajectory) app.router.add_static('/', path=str(PROJ_ROOT / 'static')) return app
async def init(loop): middle = [] if DEBUG: middle.append(aiohttp_debugtoolbar.middleware) app = web.Application(loop=loop, middlewares=middle) app['websockets'] = [] app['redis'] = {} # {} 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 app.on_shutdown.append(on_shutdown) handler = app.make_handler() pool = await aioredis.create_pool(('127.0.0.1', 6379), minsize=1, maxsize=40, loop=loop) serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app, pool
def create_app(): import aiohttp_debugtoolbar app = init_app() aiohttp_debugtoolbar.setup(app) return app
def create_app(config=None): if not config: config = get_config() cpu_count = multiprocessing.cpu_count() loop = asyncio.get_event_loop() if config['DEBUG']: middlewares.append(toolbar_middleware_factory) app = web.Application(loop=loop, middlewares=middlewares) if config['DEBUG']: aiohttp_debugtoolbar.setup(app) app['executor'] = ProcessPoolExecutor(cpu_count) app['config'] = config # app.rmq = RabbitConnector(app['config'], app.loop) # app.loop.run_until_complete(app.rmq.connect(channel_number=2)) app.on_startup.append(init_database) app.on_startup.append(init_redis) app.on_startup.append(start_background_tasks) app.on_cleanup.append(cleanup_background_tasks) setup_routes(app) setup_swagger(app, swagger_url='/api/v1/doc') return app
async def init(): # secret_key must be 32 url-safe base64-encoded bytes fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) app = web.Application(middlewares=[ session_middleware(EncryptedCookieStorage(secret_key)), authorize, db_handler, # aiohttp_debugtoolbar.middleware, ]) app['websockets'] = [] if DEBUG: aiohttp_debugtoolbar.setup(app) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) for (method, path, handler, name) in routes: app.router.add_route(method, path, handler, name=name) app.router.add_static('/static', 'static', name='static') # db connect app.client = motor_asyncio.AsyncIOMotorClient(MONGO_HOST) app.db = app.client[MONGO_DB_NAME] # end db connect app.on_shutdown.append(shutdown) return app
async def init(loop): app = web.Application(loop=loop, middlewares=[ session_middleware( EncryptedCookieStorage(SECRET_KEY)), authorize, db_handler, aiohttp_debugtoolbar.middleware, ]) app['websockets'] = defaultdict(list) handler = app.make_handler() if DEBUG: aiohttp_debugtoolbar.setup(app, intercept_redirects=False) 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.db = await init_db(host=MYSQL_HOST, db=MYSQL_DB_NAME, user=MYSQL_USER, password=MYSQL_PASSWORD, loop=loop) # 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 enable_debugger(app): """ provides a debug toolbar for server requests """ import aiohttp_debugtoolbar # dev mode only # this will be served at API_SERVER_URL/_debugtoolbar aiohttp_debugtoolbar.setup(app)
async def init(loop): app = web.Application(loop=loop, middlewares=[ session_middleware(EncryptedCookieStorage(SECRET_KEY)), authorize, db_handler, # aiohttp_debugtoolbar.middleware, ]) # 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) app['websockets'] = [] handler = app.make_handler() if DEBUG: aiohttp_debugtoolbar.setup(app) aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) serv_generator = loop.create_server(handler, SITE_HOST, SITE_PORT) return serv_generator, handler, app
def create_app(argv) -> web.Application: """App factory. Sets up routes and all plugins. """ middle = [ # error_middleware, auth_middleware, ] if settings.DEBUG: middle.append(aiohttp_debugtoolbar.middleware) app = web.Application(middlewares=middle, debug=settings.DEBUG) app['websockets'] = [] if settings.DEBUG: aiohttp_debugtoolbar.setup(app) app.on_shutdown.append(on_shutdown) # Set up routes routes.setup(app) # Use content negotiation middleware to render JSON responses negotiation.setup(app) from models.main import client, db app.client = client app.db = db app.synchronize_indexes = synchronize_indexes setup_scheduler(app) 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 main(host, port, debug): logging.basicConfig(level=logging.DEBUG) loop = asyncio.get_event_loop() app = loop.run_until_complete(get_app()) if debug: import aiohttp_debugtoolbar aiohttp_debugtoolbar.setup(app) web.run_app(app, host=host, port=port)
def app(loop=None, CONFIG='config.debug'): loop = loop if loop else asyncio.get_event_loop() _app = WorkerApp('worker', CONFIG=CONFIG, loop=loop) if _app.cfg.DEBUG: aiohttp_debugtoolbar.setup(_app) register_routes(_app, api_views, url_prefix='/api') asyncio.ensure_future(_app.queue_consumer.connect(), loop=loop) return _app
def init(loop): # add aiohttp_debugtoolbar middleware to you application app = web.Application(loop=loop) extra_panels = [] if 'aiopg' in sys.modules: extra_panels.append(RequestPgDebugPanel) if 'aioredis' in sys.modules: extra_panels.append(RequestRedisDebugPanel) # install aiohttp_debugtoolbar aiohttp_debugtoolbar.setup(app, extra_panels=extra_panels, extra_templates=str(PATH_PARENT / 'extra_tpl')) template = """ <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ text }}</h1> <p> <a href="{{ app.router['exc_example'].url_for() }}"> 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') if 'aiopg' in sys.modules: # create connection to the database dsn = 'host={host} dbname={db} user={user} password={passw} '.format( db='postgres', user='******', passw='1', host='localhost') app['db'] = yield from aiopg.create_pool(dsn, loop=loop, minsize=1, maxsize=2) # Correct PostgreSQL shutdown app.on_cleanup.append(close_pg) if 'aioredis' in sys.modules: # create redis pool app['redis'] = yield from create_pool(('127.0.0.1', '6379')) # Correct Redis shutdown app.on_cleanup.append(close_redis) 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_app(): app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('./views')) if platform.system() == "Windows": aiohttp_debugtoolbar.setup(app) app['client_session'] = aiohttp.ClientSession( headers={"User-Agent": "RickBot-ImageGeneration/0.0.1a"}) app.router.add_routes(route) return app
def init(loop): # add aiohttp_debugtoolbar middleware to you application app = web.Application(loop=loop) extra_panels = [] if 'aiopg' in sys.modules: extra_panels.append(RequestPgDebugPanel) if 'aioredis' in sys.modules: extra_panels.append(RequestRedisDebugPanel) # install aiohttp_debugtoolbar aiohttp_debugtoolbar.setup( app, extra_panels=extra_panels, extra_templates=str(PATH_PARENT / 'extra_tpl')) template = """ <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ text }}</h1> <p> <a href="{{ app.router['exc_example'].url_for() }}"> 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') if 'aiopg' in sys.modules: # create connection to the database dsn = 'host={host} dbname={db} user={user} password={passw} '.format( db='postgres', user='******', passw='1', host='localhost') app['db'] = yield from aiopg.create_pool( dsn, loop=loop, minsize=1, maxsize=2) # Correct PostgreSQL shutdown app.on_cleanup.append(close_pg) if 'aioredis' in sys.modules: # create redis pool app['redis'] = yield from create_pool(('127.0.0.1', '6379')) # Correct Redis shutdown app.on_cleanup.append(close_redis) 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 modify_main_app(app, config: Config): """ Modify the app we're serving to make development easier, eg. * modify responses to add the livereload snippet * set ``static_root_url`` on the app * setup the debug toolbar """ app._debug = True dft_logger.debug('livereload enabled: %s', '✓' if config.livereload else '✖') def get_host(request): if config.infer_host: return request.headers.get('host', 'localhost').split(':', 1)[0] else: return config.host if config.livereload: async def on_prepare(request, response): if (not request.path.startswith('/_debugtoolbar') and 'text/html' in response.content_type and getattr(response, 'body', False)): lr_snippet = LIVE_RELOAD_HOST_SNIPPET.format( get_host(request), config.aux_port) dft_logger.debug('appending live reload snippet "%s" to body', lr_snippet) response.body += lr_snippet.encode() app.on_response_prepare.append(on_prepare) static_path = config.static_url.strip('/') # we set the app key even in middleware to make the switch to production easier and for backwards compat. if config.infer_host: async def static_middleware(app, handler): async def _handler(request): static_url = 'http://{}:{}/{}'.format(get_host(request), config.aux_port, static_path) dft_logger.debug('settings app static_root_url to "%s"', static_url) app['static_root_url'] = static_url return await handler(request) return _handler app.middlewares.insert(0, static_middleware) static_url = 'http://{}:{}/{}'.format(config.host, config.aux_port, static_path) dft_logger.debug('settings app static_root_url to "%s"', static_url) app['static_root_url'] = static_url if config.debug_toolbar: aiohttp_debugtoolbar.setup(app, intercept_redirects=False)
def setup_admin_app(app, loop): admin = web.Application(loop=loop) aiohttp_debugtoolbar.setup(admin) add_static_handlers(admin) aiohttp_jinja2.setup( admin, loader=jinja2.FileSystemLoader(TEMPLATE_DIR + '/admin'), ) add_admin_handlers(admin) app.add_subapp('/admin/', admin)
def init_app(self): app = web.Application(middlewares=[self.error_middleware]) app.router.add_get("/", self.health) app.router.add_get("/amount/get", self.amount_get) app.router.add_post("/amount/set", self.amount_set) app.router.add_get("/{name}/get", self.get_currency) app.router.add_post("/{name}/set", self.set_currency) app.router.add_post("/modify", self.modify_currency) aiohttp_debugtoolbar.setup(app) return app
async def get_app(db_access_vars, debug): app = web.Application(debug=debug) app = await add_connection_pool(app, db_access_vars) setup_routes(app) if debug: aiohttp_debugtoolbar.setup(app) return app
def create_app(self) -> web.Application: mw = self.get_middlewares() app = web.Application(middlewares=mw, debug=settings.DEBUG) if settings.USE_DEBUG_TOOLBAR: try: import aiohttp_debugtoolbar aiohttp_debugtoolbar.setup(app) except ImportError: logger.warning("Can't init aiohttp_debugtoolbar") return app
async def init(loop): app = web.Application(loop=loop, middlewares=create_middlewares_list()) if DEBUG_MODE: aiohttp_debugtoolbar.setup(app) for i in routerutil.routes_list: app.router.add_route(*i) srv = await loop.create_server(app.make_handler(), HOST_ADDR, HOST_PORT) print("Server started at http://{0}:{1}".format(HOST_ADDR, HOST_PORT)) return srv
def app(loop=None, CONFIG='config.debug'): loop = loop if loop else asyncio.get_event_loop() _app = WorkerApp( 'worker', CONFIG=CONFIG, loop=loop ) if _app.cfg.DEBUG: aiohttp_debugtoolbar.setup(_app) register_routes(_app, api_views, url_prefix='/api') asyncio.ensure_future(_app.queue_consumer.connect(), loop=loop) return _app
def __init__(self, repository, *args, **kwargs): super().__init__(*args, **kwargs) self.repository = repository self._register_handlers() self._register_static() self._register_templates() if config.DEBUG: aiohttp_debugtoolbar.setup(self) self.on_shutdown.append(self.close)
async def get_app(debug=False): # Graceful shutdown actions async def close_redis(app): keys = await app['redis'].keys('channels*:users') # Can`t perform action like that: # await app['redis'].delete(*keys) for key in keys: await app['redis'].delete(key) log.server_logger.info('Closing redis') app['redis'].close() async def close_websockets(app): for channel in app['waiters'].values(): while channel: ws = channel.pop() await ws.close(code=1000, message='Server shutdown') middlewares = [auth_cookie_factory] if debug: middlewares += [toolbar_middleware_factory] app = web.Application(middlewares=middlewares) if debug: aiohttp_debugtoolbar.setup(app, intercept_redirects=False) router = app.router router.add_route('GET', '/', handlers.index_handler) router.add_route('*', '/login', handlers.LoginView) router.add_route('GET', '/logout', handlers.logout_handler) router.add_route('GET', '/channels/{channel}/', handlers.index_handler) router.add_route('GET', '/chat/{channel}/', handlers.websocket_handler) router.add_static('/static', 'static') aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates/semantic'), context_processors=[static_processor, auth_processor]) app['redis'] = await aioredis.create_redis(('localhost', 6379), db=1, encoding='utf-8') app['waiters'] = defaultdict(BList) app.on_shutdown.append(close_websockets) app.on_shutdown.append(close_redis) return app
def app(loop=None, CONFIG='config.debug'): loop = loop if loop else asyncio.get_event_loop() _app = BackendApp( 'backend', CONFIG=CONFIG, middlewares=[request_check], loop=loop ) if _app.cfg.DEBUG: aiohttp_debugtoolbar.setup(_app) register_routes(_app, api_views, url_prefix='/api') register_routes(_app, selenium_views, url_prefix='/wd/hub') asyncio.ensure_future(_app.queue_producer.connect(), loop=loop) return _app
def create(*, debug=False, ssl_ctx=None, **kw): app = web.Application(loop=loop) setup(app, **kw) tplt = """ <html> <head></head> <body> <h1>{{ head }}</h1>{{ text }} </body> </html>""" loader = jinja2.DictLoader({'tplt.html': tplt}) aiohttp_jinja2.setup(app, loader=loader) return app
def create(*, debug=False, ssl_ctx=None, **kw): nonlocal app, app_handler, srv app = web.Application(loop=loop) setup(app, **kw) port = unused_port tplt = "<html><body><h1>{{ head }}</h1>{{ text }}</body></html>" loader = jinja2.DictLoader({'tplt.html': tplt}) aiohttp_jinja2.setup(app, loader=loader) app_handler = app.make_handler(debug=debug, keep_alive_on=False) srv = yield from loop.create_server(app_handler, '127.0.0.1', port, ssl=ssl_ctx) proto = "https" if ssl_ctx else "http" url = "{}://127.0.0.1:{}".format(proto, port) return app, url
def application(loop=None): middlewares = [ minify_middleware, error_middleware, flash_middleware, ] if getattr(config, 'test', None): storage = SimpleCookieStorage() else: storage = EncryptedCookieStorage(config.session_key) middlewares.append(session_middleware(storage)) app = web.Application(loop=loop, middlewares=middlewares, debug=config.debug) app.mcache = aiomcache.Client(*config.memcache['server'], loop=loop) if config.debug: import aiohttp_debugtoolbar aiohttp_debugtoolbar.setup(app, intercept_redirects=False) app.config = config engine.setup(app, context_processors=[context_processor, engine.request_processor], loader=jinja2.FileSystemLoader('./template')) app.router \ .add_resource('/', name='home') \ .add_route('GET', home) app.router \ .add_resource('/contact', name='contact') \ .add_route('POST', contact) app.router \ .add_resource('/callback', name='callback') \ .add_route('POST', callback) app.router \ .add_resource('/ws', name='chat') \ .add_route('GET', ws) app.router.add_route('GET', '/wsh', ws_handler) return app
def init_app(): _settings = get_settings() middlewares = [] if _settings.DEBUG and _settings.DEBUG_TOOLBAR: middlewares.append(aiohttp_debugtoolbar.middleware) app = web.Application(middlewares=middlewares, debug=_settings.DEBUG) app.settings = _settings discover_urls(app) urlconf.setup(app) templating.setup(app) assets.setup(app) if app.settings.DEBUG: if _settings.DEBUG_TOOLBAR: aiohttp_debugtoolbar.setup(app) app.router.add_static(_settings.STATIC_URL, _settings.STATIC_PATH) return app
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
import aiohttp_debugtoolbar from aiohttp import web import settings from middlewares import MIDDLEWARES from helpers import add_routes from urls import routes if __name__ == '__main__': app = web.Application(debug=settings.DEBUG, middlewares=MIDDLEWARES) if settings.DEBUG: aiohttp_debugtoolbar.setup(app) add_routes(app, routes) web.run_app(app, port=settings.PORT)
def test_setup_only_adds_middleware_if_not_already_added(loop): app = web.Application(loop=loop, middlewares=[aiohttp_debugtoolbar.middleware]) aiohttp_debugtoolbar.setup(app) assert app.middlewares == [aiohttp_debugtoolbar.middleware]
import asyncio import aiohttp_debugtoolbar from src.app import app aiohttp_debugtoolbar.setup(app, intercept_redirects=False) loop = asyncio.get_event_loop() handler = app.make_handler() f = loop.create_server(handler, '127.0.0.1', 8080) srv = loop.run_until_complete(f) print('serving on', srv.sockets[0].getsockname()) try: loop.run_forever() except KeyboardInterrupt: pass finally: loop.run_until_complete(handler.finish_connections(1.0)) srv.close() loop.run_until_complete(srv.wait_closed()) loop.run_until_complete(app.finish()) loop.close()