Exemplo n.º 1
0
def run(argv):
    args = _parse_argv(argv)
    app = web.Application(middlewares=[
        main,
    ])
    app.router.add_view("/search", AggregatorOfSearchEngines)
    app.on_startup.append(_create_scheme)
    setup_jinja2(app=app, loader=FileSystemLoader("app/static"))

    web.run_app(app, host=args.host, port=args.port)
Exemplo n.º 2
0
async def init_app(argv=None):
    app = web.Application()

    setup_routes(app)
    setup_jinja2(app, loader=FileSystemLoader(BASE_PATH / 'templates'))
    setup_swagger(app, swagger_url="/api/v1/doc", ui_version=2)
    setup_aiohttp_apispec(app=app,
                          title="Profiles documentation",
                          version="v1",
                          url="/api/docs/swagger.json",
                          swagger_path="/api/docs",
                          static_path="/api/static")
    setup_middlewares(app)
    setup_db(app, dsn=dsn)

    return app
Exemplo n.º 3
0
async def init_app(loop):
    host = '0.0.0.0'
    port = 5000

    app = Application(loop=loop, middlewares=[
        toolbar_middleware_factory,
        security_log_middleware,
    ])
    # Create a database connection pool
    app['pool'] = await asyncpg.create_pool(database='vagga', user='******', port=5433)
    app['redis_pool'] = await aioredis.create_pool(('localhost', 6379))

    app.router.add_route('GET', '/', root_handler.index)
    app.router.add_route('GET', '/login', root_handler.login)
    app.router.add_route('POST', '/login', root_handler.login)
    app.router.add_route('GET', '/logout', root_handler.logout)
    app.router.add_route('GET', '/profile', root_handler.profile)
    app.router.add_route('POST', '/profile', root_handler.profile)

    app.router.add_route('GET', '/admin', admin_handler.index)
    app.router.add_route('GET', '/admin/', admin_handler.index)
    app.router.add_route('GET', '/admin/categories', admin_handler.categories)
    app.router.add_route('GET', '/admin/category/create', admin_handler.create_category)
    app.router.add_route('POST', '/admin/category/create', admin_handler.create_category)
    app.router.add_route('GET', '/admin/category/{id:\d+}/edit', admin_handler.edit_category)
    app.router.add_route('POST', '/admin/category/{id:\d+}/edit', admin_handler.edit_category)
    app.router.add_route('GET', '/admin/security_log', admin_handler.security_log)

    app.router.add_route('GET', '/notes', notes_handler.index)
    app.router.add_route('GET', '/notes/', notes_handler.index)
    app.router.add_route('GET', '/notes/{cat}/notes', notes_handler.category)
    app.router.add_route('GET', '/notes/create', notes_handler.create_note)
    app.router.add_route('POST', '/notes/create', notes_handler.create_note)
    app.router.add_route('GET', '/notes/{id:\d+}/read', notes_handler.read)

    setup_jinja2(
        app,
        context_processors=[user_processor, request_processor],
        loader=FileSystemLoader('app/templates')
    )

    aiohttp_debugtoolbar.setup(app, intercept_redirects=False)

    handler = app.make_handler()
    srv = await loop.create_server(handler, host, port)

    return srv, handler
Exemplo n.º 4
0
def create_app(argv: List[str] = None) -> web.Application:
    upload_path = Path(tempfile.gettempdir()) / "aiohttp-tus-example-uploads"
    upload_path.mkdir(mode=0o755, exist_ok=True)

    app = setup_tus(
        web.Application(client_max_size=get_client_max_size()),
        upload_path=upload_path,
    )
    app[APP_UPLOAD_PATH_KEY] = upload_path
    setup_jinja2(app,
                 loader=jinja2.FileSystemLoader(
                     Path(__file__).parent / "templates"))

    app.router.add_get("/", views.index)
    app.on_shutdown.append(remove_upload_path)

    print("aiohttp-tus example app")
    print(f"Uploading files to {upload_path.absolute()}\n")

    return app
Exemplo n.º 5
0
 async def _setup(self):
     self._app["ws_conn"] = {}
     self._app["loop"] = self._loop
     self._app["is_shutdowning"] = False
     self._app["ws_url"] = str(self._listen.with_scheme("ws").with_path("ws"))
     self._app.on_cleanup.append(close_tasks)
     self._app.on_shutdown.append(shutdown_ws_connect)
     self._app.router.add_view("/factorial/", FactorialHandler)
     self._app.router.add_static(
         prefix="/static",
         path="app/static",
         name="static",
     )
     setup_jinja2(app=self._app, loader=FileSystemLoader("app/static/"))
     await self._runner.setup()
     self.site = web.TCPSite(
         self._runner,
         self._listen.host,
         self._listen.port,
     )
     await self.site.start()
Exemplo n.º 6
0
async def init_app(loop, config_filename):
    config = read_config(config_filename)
    host = config['app']['host']
    port = config['app']['port']

    configure_logging()
    
    # Set up database
    client = AsyncIOMotorClient(
        config['mongo']['host'],
        config['mongo']['port'],
    )
    mongo_db_name = config['mongo']['db']
    db = client[mongo_db_name]

    app = Application(loop=loop)
    app.db = db
    # FIXME: find a better way to configure templates folder
    setup_jinja2(app, loader=jinja2.FileSystemLoader('app/templates'))

    # Setup views
    app.router.add_route('GET', '/', root_handler.index)
    app.router.add_route('GET', '/about', root_handler.about)
    app.router.add_route('GET', '/api/misc/{id}', api_misc_handler.get)
    app.router.add_route('POST', '/api/misc/', api_misc_handler.create)
    app.router.add_static('/static', config['app']['static-dir'])

    handler = app.make_handler()

    srv = await loop.create_server(handler, host, port)

    log.info(
        'App started at http://%(host)s:%(port)s',
        {'host': host, 'port': port}
    )
    return srv, handler
Exemplo n.º 7
0
async def init(loop):
    redis_pool = await create_pool(('localhost', 6379))
    db_engine = await create_engine(user=settings.DB_USER,
                                    password=settings.DB_PASSWORD,
                                    database=settings.DATABASE,
                                    host=settings.DB_HOST)
    app = web.Application(loop=loop)
    app['engine'] = db_engine
    setup_debugtoolbar(app)
    setup_session(app, RedisStorage(redis_pool))
    setup_security(app,
                   SessionIdentityPolicy(),
                   DBAuthorizationPolicy(db_engine))
    setup_jinja2(app, loader=jinja2.FileSystemLoader('demo/templates'))

    auth_handlers = AuthHandlers()
    auth_handlers.configure(app)
    if settings.DEBUG:
        app.router.add_static('/static', path=str(PROJ_ROOT / 'static'))
    view_handlers = ViewsHandlers()
    view_handlers.configure(app)
    admin_config = str(PROJ_ROOT / 'static' / 'js')
    setup_admin(app, db_engine, admin_config)
    return app
Exemplo n.º 8
0
def setup_app(loop=asyncio.get_event_loop(), config=load_config()[0]):
    if config.get("sentry_dsn", None):
        sentry_sdk.init(
            dsn=config["sentry_dsn"],
            integrations=[AioHttpIntegration()],
            release=f"cherrydoor@{__version__}",
        )
    # create app
    app = web.Application(loop=loop)
    # make config accessible through the app
    app["config"] = config
    # setup database and add it to the app
    db = init_db(config, loop)
    app["db"] = db
    # create a token generator/validator and add make it accessible through the app
    api_tokens = ApiTokens(app, config.get("secret_key", ""))
    app["api_tokens"] = api_tokens

    app.on_startup.append(setup_db)
    # set up aiohttp-session with aiohttp-session-mongo for storage
    setup_session(
        app,
        MongoStorage(
            db["sessions"],
            max_age=None,
            cookie_name="session_id",
        ),
    )
    # set up aiohttp-security
    setup_security(
        app,
        SessionIdentityPolicy("uid", config.get("max_session_age", 31536000)),
        AuthorizationPolicy(app),
    )
    # set up secure.py
    secure_setup(app)
    app.middlewares.append(set_secure_headers)

    csrf_policy = aiohttp_csrf.policy.FormAndHeaderPolicy(
        CSRF_HEADER_NAME, CSRF_FIELD_NAME
    )
    csrf_storage = aiohttp_csrf.storage.SessionStorage(CSRF_SESSION_NAME)
    aiohttp_csrf.setup(app, policy=csrf_policy, storage=csrf_storage)
    # app.middlewares.append(aiohttp_csrf.csrf_middleware)

    load_and_connect_all_endpoints_from_folder(
        path=f"{os.path.dirname(os.path.realpath(__file__))}/api",
        app=app,
        version_prefix="api/v1",
    )
    redoc_url = "/api/v1/docs"
    setup_redoc(
        app,
        redoc_url=redoc_url,
        description=openapi_description,
        title="Cherrydoor API",
        page_title="Cherrydocs",
        openapi_info=get_openapi_documentation(overrides=openapi_overrides),
        redoc_options=redoc_options,
        contact=openapi_contact,
    )
    app["redoc_url"] = redoc_url
    app.router.add_routes(redoc_routes)
    setup_static_routes(app)

    jinja2_loader = PackageLoader("cherrydoor", "templates")
    setup_jinja2(app, loader=jinja2_loader, auto_reload=True)
    get_env(app).globals["sri"] = sri_for
    get_env(app).globals["csrf_field_name"] = CSRF_FIELD_NAME
    get_env(app).filters["vue"] = vue
    setup_routes(app)
    sio.attach(app)
    app.on_startup.append(setup_socket_tasks)

    return app