def main(): print("main ok\n") loop = asyncio.get_event_loop() # searchCom() from handlers.main import page_handler app = aiohttp.web.Application(loop=loop) app.router.add_route("*", "/", page_handler) cors = aiohttp_cors.setup(app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*", ) }) for route in list(app.router.routes()): if route._method != '*': cors.add( route, { "*": aiohttp_cors.ResourceOptions( allow_credentials=True, allow_headers="*", ) }) aiohttp_autoreload.start() aiohttp.web.run_app(app, host=config['host'], port=config['port'])
def create_app(config: 'dict') -> 'Application': """Create server application and all necessary services. :param config: server settings """ logger_configure( level=config['LOG_LEVEL'], root_level=config['LOG_ROOT_LEVEL']) app = Application(debug=config['DEBUG']) app['config'] = config if config['DEBUG'] and not config['TESTING']: log.warning('Run in DEBUG mode!') aiohttp_autoreload.start() api_app = Application() app['api'] = api_app register_routes(api_app, routes['/api']) app.add_subapp('/api', api_app) register_routes(app, routes['/']) return app
def _start(config): logging.basicConfig(level=logging.INFO, format='%(asctime)s [{name}] %(message)s'.format( name=config['node']['name'])) logging.info('config: ' + json.dumps(config, indent=2)) app = web.Application() app.add_routes([ web.get('/api/v1/status', cluster_status), web.get('/api/v1/dev/cs', dev_cluster_state), web.post('/api/v1/dev/readonly', dev_readonly), web.get('/api/v1/logs', list_logs), web.get('/api/v1/nodes', list_nodes), web.post('/api/v1/log/{log_id}', create), web.post('/api/v1/log/{log_id}/replicate', replicate_log), web.get('/api/v1/log/{log_id}/status', log_status), web.get('/api/v1/log/{log_id}/query', query) ]) local_logs = LocalLogs(config['data_dir']) cluster = Cluster(config, config['network']['bind'], config['network']['peers']) cluster.set_local_logs(local_logs) cluster.start() app['config'] = config app['cluster'] = cluster app['data_dir'] = pathlib.Path(config['data_dir']) app['local_logs'] = local_logs host = config['network']['bind'] app['self_addr'] = host aiohttp_autoreload.start() web.run_app(app, host=host, port=config['network']['app_port'])
def run_server(conf): for cfg in vars(conf): if cfg[:2] != "__": config.set(cfg, getattr(conf, cfg)) # Setup database config for later use conn.setup(config.get("DATABASE", {})) # Resolve middleware middleware = [resolve_func(func) for func in config.get("MIDDLEWARE", [])] server = web.Application(middlewares=middleware) logger = logging.getLogger("brink") # Iterate over all installed apps and add their routes for app in config.get("INSTALLED_APPS", []): __load_app(server, app) # Enable source code auto reload on change only if DEBUG is enabled if config.get("DEBUG"): aiohttp_autoreload.add_reload_hook( lambda: print("\nDetected code change. Reloading...\n")) aiohttp_autoreload.start() logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) logger.addHandler(ch) server.make_handler(access_log=logger) port = config.get("PORT", 8888) print("🌍 Server listening on port %s\n" % port) web.run_app(server, port=port, print=lambda *args: None)
def run(self, arguments, settings, app): if arguments.monitor: if not HAS_AIOMONITOR: sys.stderr.write( 'You must install aiomonitor for the ' '--monitor option to work.\n' 'Use `pip install aiomonitor` to install aiomonitor.\n') return 1 # init monitor just before run_app loop = self.get_loop() with aiomonitor.start_monitor(loop=loop): self._run(arguments, settings, app) if arguments.reload: if not HAS_AUTORELOAD: sys.stderr.write( 'You must install aiohttp_autoreload for the --reload option to work.\n' 'Use `pip install aiohttp_autoreload` to install aiohttp_autoreload.\n' ) return 1 aiohttp_autoreload.start() self._run(arguments, settings, app) if self.profiler is not None: if arguments.profile_output: self.profiler.dump_stats(arguments.profile_output) else: # dump to screen self.profiler.print_stats(-1) if self.line_profiler is not None: self.line_profiler.disable_by_count() if arguments.line_profiler_output: self.line_profiler.dump_stats(arguments.line_profiler_output) else: self.line_profiler.print_stats()
def main(argv=None): if argv is None: argv = sys.argv parser = argparse.ArgumentParser(description='LabxDB app.') parser.add_argument('--host', action='store', help='Host') parser.add_argument('--port', action='store', default=8090, help='Port', type=int) parser.add_argument('--static_path', action='store', default='static', help='Static path') parser.add_argument('--debug', action='store_true', default=False, help='Debug') parser.add_argument('--db_host', action='store', default='', help='Database host') parser.add_argument('--db_port', action='store', type=int, default=5432, help='Database port') parser.add_argument('--db_name', action='store', default='', help='Database name') parser.add_argument('--db_user', action='store', default='', help='Database user') parser.add_argument('--db_password', action='store', default='', help='Database password') parser.add_argument('--db_conn', action='store', type=int, default=1, help='Database connection number') args = parser.parse_args(argv[1:]) # Add arguments to environment for k, v in vars(args).items(): os.environ[ENV_PREFIX+k.upper()] = str(v) # Logging if args.debug: logging.basicConfig(level=logging.DEBUG) try: import aiohttp_autoreload aiohttp_autoreload.start() except: print('Live-reload failed') # Application app = create_app() aiohttp.web.run_app(app, host=args.host, port=args.port)
async def create_server(self, loop, app, host, port): if getattr(app, 'debug_mode', None): aiohttp_autoreload.start() protocol = functools.partial(http.HttpProtocol, consumer=app, loop=loop) server = await loop.create_server(protocol, host=host, port=port) self.servers.append(server)
def wrapper(autoreload: bool, *args, **kwargs): if autoreload and aiohttp_autoreload: logger.warning( "Application started in live-reload mode. Please disable it in production!" ) aiohttp_autoreload.start() elif autoreload and not aiohttp_autoreload: click.echo("`aiohttp_autoreload` is not installed.", err=True) return func(*args, **kwargs)
def wrapper(autoreload: bool, *args, **kwargs): if autoreload and aiohttp_autoreload: logger.warning( "Bot started in Debug-Mode. make sure to disable this in production!" ) aiohttp_autoreload.start() elif autoreload and not aiohttp_autoreload: click.echo("`aiohttp_autoreload` is not installed.", err=True) return func(*args, **kwargs)
def __init__(self, loop, app, app_name): self.app = app self.loop = loop self.app_name = app_name setattr(self.app, 'config', Config()) self.app.config.from_object(configure_class) # 修改代码时会自动重启 if self.app.config['DEBUG']: aiohttp_autoreload.start()
def main(): global loop # setup loop = asyncio.get_event_loop() app = init() handler = app.make_handler(debug=debug) loop.run_until_complete(loop.create_server(handler, '0.0.0.0', 8080)) print('======= Private Server running at :8080 =======') if debug: print('debug enabled, auto-reloading enabled') aiohttp_autoreload.start() # Run server loop.run_forever()
def main(): global loop # setup loop = asyncio.get_event_loop() app = init() handler = app.make_handler(debug=debug) loop.run_until_complete(loop.create_server(handler, '0.0.0.0', 8080)) print('======= Private Server running at :8080 =======') if debug: print('debug enabled, auto-reloading enabled') aiohttp_autoreload.start() # Run server loop.run_forever()
def main(app=None): # setup if app is None: app = init() if DEBUG: import aiohttp_autoreload print('debug enabled, auto-reloading enabled') aiohttp_autoreload.start() # Run server def handle_signal(*args): raise KeyboardInterrupt signal.signal(signal.SIGINT, handle_signal) web.run_app(app, port=8445)
def run(self, arguments, settings, app): if arguments.monitor: if not HAS_AIOMONITOR: return print('You must install aiomonitor for the --monitor option to work' 'Use `pip install aiomonitor` to install aiomonitor.') # init monitor just before run_app loop = self.get_loop() with aiomonitor.start_monitor(loop=loop): self._run(arguments, settings, app) if arguments.reload: if not HAS_AUTORELOAD: return print('You must install aiohttp_autoreload for the --reload option to work' 'Use `pip install aiohttp_autoreload` to install aiohttp_autoreload.') aiohttp_autoreload.start() self._run(arguments, settings, app)
def main(): # uvloop を用いてのasyncio高速化 loop = uvloop.new_event_loop() asyncio.set_event_loop(loop) app = web.Application(loop=loop) # templates直下をjinjaでファイル読み込み aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates/')) if debug: aiohttp_autoreload.start() handler = BaseHandler() app.add_routes( [web.get('/', handler.index), web.get('/answer', handler.post)]) app.router.add_static('/statics/', path='statics', name='static') web.run_app(app)
def run(self, arguments, settings, app): if arguments.reload: if not HAS_AUTORELOAD: sys.stderr.write( "You must install aiohttp_autoreload for the --reload option to work.\n" "Use `pip install aiohttp_autoreload` to install aiohttp_autoreload.\n" ) return 1 aiohttp_autoreload.start() port = arguments.port or settings.get("address", settings.get("port")) host = arguments.host or settings.get("host", "0.0.0.0") log_format = settings.get("access_log_format", AccessLogger.LOG_FORMAT) try: web.run_app(app, host=host, port=port, access_log_format=log_format) except asyncio.CancelledError: # server shut down, we're good here. pass
def run(self, arguments, settings, app): if arguments.reload: if not HAS_AUTORELOAD: sys.stderr.write( 'You must install aiohttp_autoreload for the --reload option to work.\n' 'Use `pip install aiohttp_autoreload` to install aiohttp_autoreload.\n' ) return 1 aiohttp_autoreload.start() port = arguments.port or settings.get('address', settings.get('port')) host = arguments.host or settings.get('host', '0.0.0.0') log_format = settings.get('access_log_format', aiohttp.helpers.AccessLogger.LOG_FORMAT) try: web.run_app(app, host=host, port=port, access_log_format=log_format) except asyncio.CancelledError: # server shut down, we're good here. pass
def run(self, arguments, settings, app): if arguments.reload: if not HAS_AUTORELOAD: sys.stderr.write( 'You must install aiohttp_autoreload for the --reload option to work.\n' 'Use `pip install aiohttp_autoreload` to install aiohttp_autoreload.\n' ) return 1 aiohttp_autoreload.start() port = arguments.port or settings.get('address', settings.get('port')) host = arguments.host or settings.get('host', '0.0.0.0') try: web.run_app(app, host=host, port=port, loop=self.get_loop(), access_log_format=settings.get('access_log_format')) except asyncio.CancelledError: # server shut down, we're good here. pass
async def init(loop): global mc global app middlewares = [] # middlewares.append(aiohttp_debugtoolbar.middleware) # debugtoolbar.intercept_redirects = false middlewares.append(db_handler()) if settings.debug: middlewares.append( session_middleware(SimpleCookieStorage()) ) else: middlewares.append( session_middleware(EncryptedCookieStorage(settings.session_key)) ) app = web.Application(loop=loop, middlewares=middlewares) # aiohttp_debugtoolbar.setup(app) # debugtoolbar.intercept_redirects = False # aiohttp_debugtoolbar.intercept_redirects = False aiohttp_jinja2.setup(app, loader=jinja2.FunctionLoader(load_templ ), bytecode_cache = None, cache_size=0 ) # Memcache init app.mc = aiomcache.Client( settings.memcache['addr'], settings.memcache['port'], loop=loop) # 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') # print('path->', path) app.router.add_static('/static/', os.path.join(settings.root_path, 'static')) sites = os.path.join(settings.tao_path, 'libs', 'sites', 'st') # print('sites->', sites) app.router.add_static('/st/sites/', os.path.join(settings.tao_path, 'libs', 'sites', 'st')) app.router.add_static('/st/table/', os.path.join(settings.tao_path, 'libs', 'table', 'st')) app.router.add_static('/st/tree/', os.path.join(settings.tao_path, 'libs', 'tree', 'st')) app.router.add_static('/st/admin/', os.path.join(settings.tao_path, 'libs', 'admin', 'st')) app.router.add_static('/st/contents/', os.path.join(settings.tao_path, 'libs', 'contents', 'st')) app.router.add_static('/st/chat/', os.path.join(settings.tao_path, 'libs', 'chat', 'st')) app.router.add_static('/st/files/', os.path.join(settings.tao_path, 'libs', 'files', 'st')) app.router.add_static('/st/game/', os.path.join(settings.tao_path, 'libs', 'game', 'st')) app.router.add_static('/st/perm/', os.path.join(settings.tao_path, 'libs', 'perm', 'st')) # app.router.add_route('GET', '/static/{dir}/{fname}', st_file, name='static') handler = app.make_handler(debug=True ) if debug and reload: aiohttp_autoreload.start() srv = await loop.create_server(handler, settings.addr[0], settings.addr[1]) print("Server started at "+settings.addr[0] +' '+ str(settings.addr[1])) return srv, handler, app
def enable_reloaders(self): # Enable source code changes monitoring if settings.DEBUG and settings.DEBUG_AUTORELOAD_APP: import aiohttp_autoreload aiohttp_autoreload.start()
def run(settings, urls): app = web.Application(middlewares=[m for m in settings.MIDDLEWARE]) __add_routes(app, urls) brink.db.conn.setup(settings.RETHINKDB_CONFIG) aiohttp_autoreload.start() web.run_app(app, port=8888)
# Template engine # aiohttp_jinja2.setup(new_app, loader=jinja2.FileSystemLoader('frontend/chat/templates')) on_shutdown = [ stop_begin_log, close_websockets, ] on_cleanup = [ close_redis, stop_end_log ] new_app.on_shutdown.extend(*on_shutdown) new_app.on_cleanup.extend(*on_cleanup) return new_app if __name__ == '__main__': debug = True loop = asyncio.get_event_loop() app = loop.run_until_complete(get_app(loop)) if settings.DEBUG: aiohttp_debugtoolbar.setup(app) aiohttp_autoreload.start() web.run_app(app)
async def init(loop): global mc global app middlewares = [] # middlewares.append(aiohttp_debugtoolbar.middleware) # debugtoolbar.intercept_redirects = false middlewares.append(db_handler()) if settings.debug: middlewares.append(session_middleware(SimpleCookieStorage())) else: middlewares.append( session_middleware(EncryptedCookieStorage(settings.session_key))) app = web.Application(loop=loop, middlewares=middlewares) # aiohttp_debugtoolbar.setup(app) # debugtoolbar.intercept_redirects = False # aiohttp_debugtoolbar.intercept_redirects = False aiohttp_jinja2.setup(app, loader=jinja2.FunctionLoader(load_templ), bytecode_cache=None, cache_size=0) # Memcache init app.mc = aiomcache.Client(settings.memcache['addr'], settings.memcache['port'], loop=loop) # 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') # print('path->', path) app.router.add_static('/static/', os.path.join(settings.root_path, 'static')) sites = os.path.join(settings.tao_path, 'libs', 'sites', 'st') # print('sites->', sites) app.router.add_static( '/st/sites/', os.path.join(settings.tao_path, 'libs', 'sites', 'st')) app.router.add_static( '/st/table/', os.path.join(settings.tao_path, 'libs', 'table', 'st')) app.router.add_static( '/st/tree/', os.path.join(settings.tao_path, 'libs', 'tree', 'st')) app.router.add_static( '/st/admin/', os.path.join(settings.tao_path, 'libs', 'admin', 'st')) app.router.add_static( '/st/contents/', os.path.join(settings.tao_path, 'libs', 'contents', 'st')) app.router.add_static( '/st/chat/', os.path.join(settings.tao_path, 'libs', 'chat', 'st')) app.router.add_static( '/st/files/', os.path.join(settings.tao_path, 'libs', 'files', 'st')) app.router.add_static( '/st/game/', os.path.join(settings.tao_path, 'libs', 'game', 'st')) app.router.add_static( '/st/perm/', os.path.join(settings.tao_path, 'libs', 'perm', 'st')) # app.router.add_route('GET', '/static/{dir}/{fname}', st_file, name='static') handler = app.make_handler(debug=True) if debug and reload: aiohttp_autoreload.start() srv = await loop.create_server(handler, settings.addr[0], settings.addr[1]) print("Server started at " + settings.addr[0] + ' ' + str(settings.addr[1])) return srv, handler, app
def main(argv): logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)-8s %(message)s" ) for arg in argv: k, _, v = arg.partition("=") os.environ[k] = v logging.info("App starts...") app = web.Application() # Database from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine(os.environ["DB_DSN"], echo=False) db.Base.metadata.create_all(engine) session_factory = sessionmaker(bind=engine) @web.middleware async def add_db(request, handler): request["orm"] = session_factory() try: resp = await handler(request) finally: request["orm"].commit() request["orm"].close() return resp app.middlewares.append(add_db) populate_data(session_factory) # Templates aiohttp_mako.setup( app, directories=["./templates/"], input_encoding="utf-8", output_encoding="utf-8", default_filters=["unicode", "h"], ) # Sessions import base64 from cryptography import fernet from aiohttp_session import setup from aiohttp_session.cookie_storage import EncryptedCookieStorage if os.environ.get("SECRET"): fernet_key = os.environ["SECRET"].encode() else: fernet_key = fernet.Fernet.generate_key() print("SECRET=" + fernet_key.decode()) secret_key = base64.urlsafe_b64decode(fernet_key) setup(app, EncryptedCookieStorage(secret_key)) # Reloader try: import aiohttp_autoreload aiohttp_autoreload.start() except ImportError: pass # Setup Routes app.add_routes(routes) app.router.add_static("/static/", path="./static/", name="static") # Go! web.run_app(app, port=8000)
def enable_reloaders(self): # Enable source code changes monitoring if settings.DEBUG and settings.DEBUG_AUTORELOAD_APP: import aiohttp_autoreload aiohttp_autoreload.start()
# Jinja(template system) setup jinja_env = aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader(settings.TEMPLATE_DIR), context_processors=[aiohttp_jinja2.request_processor], ) app.add_routes(routes) app.wslist = {} return app async def close_app(): """ Cloase all connections """ app.redis_pool.close() await app.redis_pool.wait_closed() if __name__ == '__main__': loop = asyncio.get_event_loop() app = loop.run_until_complete(init_app()) if settings.DEBUG: aiohttp_autoreload.start() web.run_app(app, host=settings.APP_HOST, port=settings.APP_PORT) loop.run_until_complete(close_app()) loop.close()
nickname = request.query.get('nickname') data = await request.post() room_name = data.get('name') if room_name and nickname: await handler.leave_chat_room(room_name, nickname) return web.json_response({'status': 'success'}) def create_app(loop=None, chat_handler=None): if loop is None: loop = asyncio.get_event_loop() app = ChatApplication(loop=loop, chat_handler=chat_handler) app.router.add_get('/', index) app.router.add_get('/members', members) app.router.add_get('/rooms', rooms) app.router.add_post('/room', join_room) app.router.add_post('/join-room', join_room) app.router.add_post('/leave-room', leave_room) app.router.add_get('/style.css', css) app.router.add_get('/reconnecting-websocket.min.js', reconnecting_websocket) app.router.add_get('/ws', app.chat_handler.handle) return app if __name__ == '__main__': app = create_app() aiohttp_autoreload.start(app.loop) web.run_app(app, port=8080)