示例#1
0
def create_application() -> FastAPI:
    application = FastAPI(title=PROJECT_NAME, version=VERSION)

    # 添加事件
    application.add_event_handler("startup",
                                  create_start_app_handler(application))
    application.add_event_handler("shutdown",
                                  create_stop_app_handler(application))

    # 添加错误处理
    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError,
                                      http422_error_handler)
    application.add_exception_handler(RequestValidationError,
                                      request_validation_exception_handler)
    application.add_exception_handler(UnicornException,
                                      unicorn_exception_handler)

    # 添加中间件
    init_middlewares(application)
    application.add_middleware(CustomMiddleware)

    # 添加路由
    application.include_router(api_router)
    return application
示例#2
0
    def init_app(self,
                 app: FastAPI,
                 uri: Optional[str] = None,
                 db_name: Optional[str] = None,
                 env: str = "development") -> None:
        """Define self.app_string and add 'startup' and 'shutdown' event handlers to the given FastAPI application.

        :param app: The relevant FastAPI application
        :type app: class: FastAPI
        :param uri: Where to find the database; defaults to None, in which case localhost:27027 will be used
        :type uri: str, optional
        :param db_name: Name of the database to use; if None, a name will be generated based on the title of the FastAPI app provided to the init_app method
        :type db_name: str, optional
        :param env: The environment in which the app is running, defaults to 'development'
        :type env: str

        :raises AlreadyInitializedError: Cannot init an app that has already been initialized
        """
        async def connect():
            await self.connect_to_mongo(uri=uri, db_name=db_name)

        async def close():
            await self.close_mongo_connection()

        if any(obj is not None
               for obj in (self.app_string, self.client, self.db, self.fs,
                           self.environment)):
            raise AlreadyInitializedError("Engine is already initialized.")
        self.app_string = ''.join(c if c.isalpha() else "_"
                                  for c in list(app.title.lower()))
        self.environment = env
        app.add_event_handler("startup", connect)
        app.add_event_handler("shutdown", close)
示例#3
0
def _init_fastapi_app():
    app = FastAPI(
        title='Imune',
        description='Imune API',
        version='0.0.1',
        redoc_url=None,
    )

    app.add_middleware(
        CORSMiddleware,
        allow_origins=['*'],
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*'],
    )

    routers = [
        user_router, login_router, vaccine_router, person_router, batch_router,
        vaccinate_router, occurrence_router
    ]
    [app.include_router(**r) for r in routers]

    app.add_event_handler('startup', connect_to_mongo)
    app.add_event_handler("startup", apply_migrations)
    app.add_event_handler('shutdown', close_mongo_connection)

    app.add_exception_handler(NotFoundException, not_found_exception_handler)
    app.add_exception_handler(BusinessValidationException,
                              business_validation_exception_handler)
    app.add_exception_handler(ApiBaseException, generic_render)
    app.add_exception_handler(EnvironmentException, generic_render)
    app.add_exception_handler(LoginException, generic_render)

    return app
示例#4
0
def get_app() -> FastAPI:
    fast_app = FastAPI(title=APP_NAME, version=APP_VERSION, debug=IS_DEBUG)
    fast_app.include_router(api_router, prefix=API_PREFIX)
    fast_app.add_event_handler("startup", start_app_handler(fast_app))
    fast_app.add_event_handler("shutdown", stop_app_handler(fast_app))

    return fast_app
示例#5
0
def get_application() -> FastAPI:
    application = FastAPI(title=config.PROJECT_NAME,
                          debug=config.DEBUG,
                          version=config.VERSION)

    application.add_middleware(
        CORSMiddleware,
        allow_origins=config.ALLOWED_HOSTS or ["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    application.add_event_handler(
        "startup", events.create_startup_app_handler(application))
    application.add_event_handler(
        "shutdown", events.create_shutdown_app_handler(application))

    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError,
                                      http422_error_handler)

    application.include_router(api_router, prefix=config.API_PREFIX)

    return application
示例#6
0
def get_application():
    application = FastAPI(title='FastAPI')
    application.add_event_handler("startup", create_start_app_handler(application))
    application.add_event_handler("shutdown", create_stop_app_handler(application))
    application.include_router(api_router, prefix='/api')
    application.add_exception_handler(HTTPException, http_error_handler)
    return application
示例#7
0
def setup(app: FastAPI, settings: Optional[WebServerSettings] = None) -> None:
    if not settings:
        settings = WebServerSettings()

    assert settings is not None  # nosec

    setup_client_instance(app,
                          WebserverApi,
                          api_baseurl=settings.base_url,
                          service_name="webserver")

    # TODO: old startup. need to integrat
    # TODO: init client and then build sessions from client using depenencies

    def on_startup() -> None:
        # normalize & encrypt
        secret_key = _get_secret_key(settings)
        app.state.webserver_fernet = fernet.Fernet(secret_key)

        # init client
        logger.debug("Setup webserver at %s...", settings.base_url)

        client = AsyncClient(base_url=settings.base_url)
        app.state.webserver_client = client

    async def on_shutdown() -> None:
        with suppress(AttributeError):
            client: AsyncClient = app.state.webserver_client
            await client.aclose()
            del app.state.webserver_client
        logger.debug("Webserver closed successfully")

    app.add_event_handler("startup", on_startup)
    app.add_event_handler("shutdown", on_shutdown)
示例#8
0
def init_app(settings: Optional[AppSettings] = None) -> FastAPI:
    if settings is None:
        settings = AppSettings.create_from_envs()
    assert settings  # nosec
    logging.basicConfig(level=settings.LOG_LEVEL.value)
    logging.root.setLevel(settings.LOG_LEVEL.value)
    logger.debug(settings.json(indent=2))

    app = FastAPI(
        debug=settings.SC_BOOT_MODE
        in [BootModeEnum.DEBUG, BootModeEnum.DEVELOPMENT, BootModeEnum.LOCAL],
        title=PROJECT_NAME,
        description=SUMMARY,
        version=API_VERSION,
        openapi_url=f"/api/{API_VTAG}/openapi.json",
        docs_url="/dev/doc",
        redoc_url=None,  # default disabled
    )
    override_fastapi_openapi_method(app)

    app.state.settings = settings

    if settings.SC_BOOT_MODE == BootModeEnum.DEBUG:
        remote_debug.setup(app)

    if settings.DIRECTOR_V0.DIRECTOR_V0_ENABLED:
        director_v0.setup(app, settings.DIRECTOR_V0)

    if settings.POSTGRES.DIRECTOR_V2_POSTGRES_ENABLED:
        db.setup(app, settings.POSTGRES)

    if settings.DYNAMIC_SERVICES.DIRECTOR_V2_DYNAMIC_SERVICES_ENABLED:
        dynamic_services.setup(app, settings.DYNAMIC_SERVICES)

    if settings.DYNAMIC_SERVICES.DYNAMIC_SIDECAR and (
            settings.DYNAMIC_SERVICES.DYNAMIC_SCHEDULER
            and settings.DYNAMIC_SERVICES.DYNAMIC_SCHEDULER.
            DIRECTOR_V2_DYNAMIC_SCHEDULER_ENABLED):
        dynamic_sidecar.setup(app)

    if settings.DASK_SCHEDULER.DIRECTOR_V2_DASK_CLIENT_ENABLED:
        dask_clients_pool.setup(app, settings.DASK_SCHEDULER)

    if settings.DASK_SCHEDULER.DIRECTOR_V2_DASK_SCHEDULER_ENABLED:
        rabbitmq.setup(app)
        comp_scheduler.setup(app)

    if settings.DIRECTOR_V2_TRACING:
        setup_tracing(app, settings.DIRECTOR_V2_TRACING)

    # setup app --
    app.add_event_handler("startup", on_startup)
    app.add_event_handler("shutdown", on_shutdown)
    _set_exception_handlers(app)

    app.include_router(api_router)

    config_all_loggers()

    return app
示例#9
0
def setup_client_instance(app: FastAPI,
                          api_cls: Type[BaseServiceClientApi],
                          api_baseurl: str,
                          service_name: str,
                          api_general_timeout: float = 5.0,
                          **extra_fields) -> None:
    """Helper to add init/cleanup of ServiceClientApi instances in the app lifespam"""

    assert issubclass(api_cls, BaseServiceClientApi)

    def _create_instance() -> None:
        api_cls.create_once(app,
                            client=httpx.AsyncClient(
                                http2=True,
                                base_url=api_baseurl,
                                timeout=api_general_timeout),
                            service_name=service_name,
                            **extra_fields)

    async def _cleanup_instance() -> None:
        api_obj: Optional[BaseServiceClientApi] = api_cls.pop_instance(app)
        if api_obj:
            await api_obj.client.aclose()

    app.add_event_handler("startup", _create_instance)
    app.add_event_handler("shutdown", _cleanup_instance)
示例#10
0
def get_fastapi_app(title: str = "",
                    debug: bool = False,
                    version: str = "0.0.0"):
    initial_app = FastAPI(title=title, debug=debug, version=version)
    initial_app.add_middleware(
        CORSMiddleware,
        allow_origins=ALLOWED_HOSTS or ["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # App Startup/Shutdown Events
    initial_app.add_event_handler("startup",
                                  create_start_app_handler(initial_app))
    initial_app.add_event_handler("shutdown",
                                  create_stop_app_handler(initial_app))

    # Exception Handlers
    initial_app.add_exception_handler(HTTPException, http_error_handler)
    initial_app.add_exception_handler(RequestValidationError,
                                      http422_error_handler)

    # Add Routes
    initial_app.include_router(api_router, prefix=API_PREFIX)

    return initial_app
示例#11
0
def get_application() -> FastAPI:
    application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION)

    application.add_middleware(
        CORSMiddleware,
        allow_origins=ALLOWED_HOSTS or ["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    application.mount("/static",
                      StaticFiles(directory="static"),
                      name="static")
    application.add_event_handler("startup",
                                  create_start_app_handler(application))
    application.add_event_handler("shutdown",
                                  create_stop_app_handler(application))

    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError,
                                      http422_error_handler)

    application.include_router(api_router, prefix=API_PREFIX)
    application.include_router(html_router, prefix='')

    return application
示例#12
0
def create_app():
    logger.add(settings.LOG_FILE,
               level=settings.LOG_LEVEL,
               backtrace=settings.LOG_BACKTRACE)

    app = FastAPI(
        debug=settings.DEBUG,
        title=settings.PROJECT_NAME,
    )
    # add middleware
    app.add_middleware(GZipMiddleware, minimum_size=1000)

    # add event handlers
    app.add_event_handler("startup", create_start_app_handler(app))
    app.add_event_handler("shutdown", create_stop_app_handler(app))

    # add routes
    app.include_router(api_router, prefix="/api")
    app.mount("/static",
              StaticFiles(directory="frontend/dist/static"),
              name="static")
    app.mount("/",
              StaticFiles(html=True, directory="frontend/dist/"),
              name="index")

    return app
示例#13
0
def get_app() -> FastAPI:
    app = FastAPI()

    origin = ALLOWED_HOSTS or ["*"]

    # 开启cors (跨源资源共享)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origin,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 500字节以上开启gzip
    app.add_middleware(GZipMiddleware, minimum_size=500)

    # 添加中间件计算程序运行时间
    @app.middleware("http")
    async def add_process_time_helper(request: Request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response

    app.include_router(router, prefix=API_V1_STR)

    # 添加数据库连接和关闭事件
    app.add_event_handler("startup", connect_to_mongo)
    app.add_event_handler("shutdown", close_mongo_connection)

    return app
示例#14
0
文件: main.py 项目: PompaJokera/core
def bootstrap_app():

    app = FastAPI(title="automated terrarium dashboard API",
                  openapi_prefix=API_PREFIX)

    app.add_event_handler("startup", startup_handler)
    app.include_router(temperature.router, prefix="/sensor")
    app.include_router(humidity.router, prefix="/sensor")
    app.include_router(device.router, prefix="/device")
    app.include_router(sensor.router, prefix="/sensors")
    app.include_router(door.router, prefix="/sensor")
    app.include_router(relay.router, prefix="/relay")
    app.include_router(settings.router, prefix="/settings")
    session = base.session_factory(True)
    startup.migrate(session)
    if __debug__:
        from starlette.middleware.cors import CORSMiddleware
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
    return app
示例#15
0
def add_databases_to_app(app: FastAPI,
                         dbs: Dict[str, DatabaseDefinition]) -> FastAPI:
    """Add instances of :class:`Database` as attribute of app.

    For each database as defined in the ``config.yml`` as external-resource,
    create a :class:`Database` instance with defined parameters, add this
    instance to the ``app.databases``-attribute and add ``startup`` and
    ``shutdown`` handlers to connect / disconnect to the database on
    app-startup / app-shutdown.

    Parameters:
        app: the app to add the database definitions to.
        dbs: the databases to add to the app.

    Returns:
        modified app containing the attribute app.databases and event handler
        for startup and shutdown for the databases.

    """
    for _, db_definition in dbs.items():
        database = Database(dsn=db_definition.dsn,
                            logger=app.logger,
                            min_size=db_definition.min_size,
                            max_size=db_definition.max_size)
        app.add_event_handler('startup', database.connect)
        app.add_event_handler('shutdown', database.disconnect)
        try:
            app.databases.update({db_definition.name: database})
        except AttributeError:
            app.databases = {db_definition.name: database}
    return app
示例#16
0
def create_app():
    app = FastAPI(title=config.PROJECT_NAME,
                  debug=config.DEBUG,
                  version=config.VERSION,
                  docs_url=None,
                  redoc_url=None)

    app.add_middleware(
        CORSMiddleware,
        allow_origins=config.ALLOWED_HOSTS or ["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    add_timing_middleware(app,
                          record=logger.info,
                          prefix="solr",
                          exclude="untimed")

    app.add_event_handler("startup", create_start_app_handler())
    app.add_event_handler("shutdown", create_stop_app_handler())

    # router
    app.include_router(service_routes, prefix=config.PAGE_PREFIX)
    # app.include_router(api_routes, prefix=config.API_PREFIX)
    app.include_router(api_routes)

    init_logger()

    from src.scheduler import customized_jobs
    customized_jobs.add_a_job()

    return app
示例#17
0
def assemble_application() -> FastAPI:
    """
    Creates the application from using the env vars as a context
    Also stores inside the state all instances of classes
    needed in other requests and used to share data.
    """

    dynamic_sidecar_settings = DynamicSidecarSettings.create_from_envs()

    logging.basicConfig(level=dynamic_sidecar_settings.loglevel)
    logging.root.setLevel(dynamic_sidecar_settings.loglevel)
    logger.debug(dynamic_sidecar_settings.json(indent=2))

    application = FastAPI(
        debug=dynamic_sidecar_settings.DEBUG,
        openapi_url=f"/api/{API_VTAG}/openapi.json",
        docs_url="/dev/doc",
    )
    override_fastapi_openapi_method(application)

    # store "settings"  and "shared_store" for later usage
    application.state.settings = dynamic_sidecar_settings
    application.state.shared_store = SharedStore(
        settings=dynamic_sidecar_settings)  # type: ignore
    # used to keep track of the health of the application
    # also will be used in the /health endpoint
    application.state.application_health = ApplicationHealth()

    # enable debug if required
    if dynamic_sidecar_settings.is_development_mode:
        remote_debug_setup(application)

    if dynamic_sidecar_settings.RABBIT_SETTINGS:
        setup_rabbitmq(application)
        # requires rabbitmq to be in place
        setup_background_log_fetcher(application)

    # add routing paths
    application.include_router(main_router)

    setup_directory_watcher(application)

    def create_start_app_handler() -> Callable[[], Coroutine[Any, Any, None]]:
        async def on_startup() -> None:
            await login_registry(application.state.settings.REGISTRY_SETTINGS)
            print(WELCOME_MSG, flush=True)

        return on_startup

    def create_stop_app_handler() -> Callable[[], Coroutine[Any, Any, None]]:
        async def on_shutdown() -> None:
            await on_shutdown_handler(application)
            logger.info("shutdown cleanup completed")

        return on_shutdown

    application.add_event_handler("startup", create_start_app_handler())
    application.add_event_handler("shutdown", create_stop_app_handler())

    return application
示例#18
0
def get_application() -> FastAPI:
    application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION)
    application.include_router(api_router, prefix=API_PREFIX)
    pre_load = False
    if pre_load:
        application.add_event_handler("startup", create_start_app_handler(application))
    return application
def get_application() -> FastAPI:
    settings = get_app_settings()

    settings.configure_logging()

    application = FastAPI(**settings.fastapi_kwargs)

    application.add_middleware(
        CORSMiddleware,
        allow_origins=settings.allowed_hosts,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    application.add_event_handler(
        "startup",
        create_start_app_handler(application, settings),
    )
    application.add_event_handler(
        "shutdown",
        create_stop_app_handler(application),
    )

    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError, http422_error_handler)

    application.include_router(api_router, prefix=settings.api_prefix)

    return application
示例#20
0
def get_application() -> FastAPI:
    application = FastAPI(title=config.PROJECT_NAME,
                          debug=config.DEBUG,
                          description=config.API_DESCRIPTION,
                          version=config.VERSION,
                          docs_url=None,
                          redoc_url=None,
                          openapi_url=None)

    application.add_event_handler("startup",
                                  create_start_app_handler(application))
    application.add_event_handler("shutdown",
                                  create_stop_app_handler(application))

    try:
        application.add_middleware(
            RequestTracerMiddleware,
            exporter=AzureExporter(
                connection_string=
                f'InstrumentationKey={os.getenv("APPINSIGHTS_INSTRUMENTATIONKEY")}',
                sampler=ProbabilitySampler(1.0)))
    except Exception as e:
        logging.error(f"Failed to add RequestTracerMiddleware: {e}")

    application.add_middleware(ServerErrorMiddleware,
                               handler=generic_error_handler)
    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError,
                                      http422_error_handler)

    application.include_router(api_router)
    return application
示例#21
0
def get_app() -> FastAPI:
    rec_engine = FastAPI(title=APP_NAME, version=APP_VERSION, debug=IS_DEBUG)
    rec_engine.include_router(api_router, prefix=API_PREFIX)

    rec_engine.add_event_handler("startup", start_app_handler(rec_engine))
    rec_engine.add_event_handler("shutdown", stop_app_handler(rec_engine))

    return rec_engine
示例#22
0
def get_application(settings: Optional[ServiceSettings] = None):
    """Application factory."""

    if settings is None:
        settings = ServiceSettings()

    docs_enabled = settings.docs_enabled
    application = FastAPI(
        title=settings.app_title,
        version=settings.app_version,
        openapi_tags=OPENAPI_TAGS,
        debug=settings.fastapi_debug,
        openapi_url=settings.docs_openapi_url if docs_enabled else None,
        docs_url=settings.docs_url if docs_enabled else None,
        redoc_url=settings.docs_redoc_url if docs_enabled else None,
        openapi_prefix=settings.docs_openapi_prefix,
        root_path=settings.fastapi_root_path,
    )

    if settings.prometheus_enabled:
        application.add_middleware(
            PrometheusMiddleware,
            group_paths=settings.prometheus_group_paths,
            app_name=settings.prometheus_app_name,
            prefix=settings.prometheus_prefix,
        )

    if settings.keycloak_url is not None:
        keycloak_url = settings.keycloak_url
        realm = settings.keycloak_realm
        update_oauth2_scheme(
            f"{keycloak_url}auth/realms/{realm}/protocol/openid-connect/auth",
            f"{keycloak_url}auth/realms/{realm}/protocol/openid-connect/token",
        )

    application.add_event_handler(
        "startup", app_event_handler.start_app_handler(application, settings)
    )
    application.add_event_handler(
        "shutdown", app_event_handler.stop_app_handler(application)
    )

    application.include_router(get_router(settings))
    application.middleware("http")(request_context.add_log_context)
    application.exception_handler(HTTPException)(
        exception_handlers.http_exception_handler
    )
    application.exception_handler(RequestValidationError)(
        exception_handlers.validation_exception_handler
    )

    sentry_sdk.init(
        dsn=settings.sentry_dsn,
        sample_rate=settings.sentry_traces_sample_rate,
        release=settings.app_version,
    )

    return application
示例#23
0
def setup_tracing(app: FastAPI, tracing_settings: TracingSettings):
    async def start_app() -> None:
        settings.service_name = tracing_settings.TRACING_CLIENT_NAME
        settings.jaeger_host = tracing_settings.TRACING_THRIFT_COMPACT_ENDPOINT.host
        settings.jaeger_port = tracing_settings.TRACING_THRIFT_COMPACT_ENDPOINT.port
        setup_opentracing(app)
        app.add_middleware(OpentracingMiddleware)

    app.add_event_handler("startup", start_app)
示例#24
0
def get_app() -> FastAPI:
	logger.info("App Initialization")
	fast_app = FastAPI(title=settings.APP_NAME, version=settings.APP_VERSION)
	fast_app.include_router(api_router, prefix=settings.API_PREFIX)
	fast_app.add_event_handler("startup", start_app_handler(fast_app))
	fast_app.add_event_handler("shutdown", stop_app_handler(fast_app))
	fast_app.add_middleware(RequestContextLogMiddleware)

	return fast_app
示例#25
0
def create_app() -> FastAPI:
    application = FastAPI()

    application.add_event_handler('startup', startup_handler(application))
    application.add_event_handler('shutdown', shutdown_handler(application))

    application.include_router(router)

    return application
示例#26
0
def create_app() -> FastAPI:
    app = FastAPI(debug=settings.DEBUG)
    app.include_router(router)

    handler = StartAndStopEventHandler(app)
    app.add_event_handler("startup", handler.on_startup)
    app.add_event_handler("shutdown", handler.on_shutdown)
    app.add_middleware(AddIdentifierMiddleWare)
    return app
示例#27
0
def get_application() -> FastAPI:
    """Initialize app"""
    application = FastAPI()

    application.add_event_handler('startup', create_engine(application))
    application.add_event_handler('shutdown', close_engine(application))
    init_routes(application)

    return application
示例#28
0
def get_application() -> FastAPI:
    application = FastAPI()

    application.add_event_handler("startup", create_start_app_handler(application))
    application.add_event_handler("shutdown", create_stop_app_handler(application))

    application.include_router(api_router)

    return application
示例#29
0
def setup(app: FastAPI):
    app.add_event_handler("startup", startup)
    app.middleware("http")(add_session_to_request)

    async_sqlalchemy_url = os.getenv("async_sqlalchemy_url")
    if async_sqlalchemy_url:
        assert asyncio_support, asyncio_support_err
        app.add_event_handler("startup", asyncio_support.startup)
        app.middleware("http")(asyncio_support.add_session_to_request)
示例#30
0
def get_app() -> FastAPI:
    """FastAPI app controller"""
    fast_app = FastAPI(title=APP_NAME, version=APP_VERSION, debug=IS_DEBUG)
    instrumentator.instrument(fast_app).expose(fast_app,
                                               include_in_schema=False,
                                               should_gzip=False)
    fast_app.include_router(api_router)
    fast_app.add_event_handler("startup", start_app_handler(fast_app))
    fast_app.add_event_handler("shutdown", stop_app_handler(fast_app))
    return fast_app