Esempio n. 1
0
def get_application() -> FastAPI:
    application = FastAPI(title=config.PROJECT_NAME,
                          docs_url="/api/docs",
                          openapi_url="/api")
    register_tortoise(
        application,
        db_url=DATABASE_URL,
        modules={"models": [MODELS_MODULE]},
        generate_schemas=True,
        add_exception_handlers=True,
    )

    # Routers
    application.include_router(
        router,
        prefix="/api",
    )

    @application.websocket("/ws/{queue_id}")
    async def websocket_endpoint(websocket: WebSocket, queue_id: str):
        redis = await aioredis.create_redis_pool('redis://redis',
                                                 encoding="utf-8")
        await websocket.accept()
        while True:
            res = await redis.subscribe(queue_id)
            channel = res[0]
            while await channel.wait_message():
                msg = await channel.get_json()
                await websocket.send_text(msg)

    return application
Esempio n. 2
0
def init_db(app):
    register_tortoise(
        app,
        config=DB_CONFIG,
        generate_schemas=True,
        add_exception_handlers=True,
    )
def init_db(app):
    """
	Init database models.
	:param app:
	:return:
	"""
    register_tortoise(app,
                      config={
                          "connections": {
                              "default": {
                                  "engine": "tortoise.backends.mysql",
                                  "credentials": {
                                      "database": 'local2',
                                      "host": "127.0.0.1",
                                      "password": None,
                                      "port": 3306,
                                      "user": "******"
                                  }
                              }
                          },
                          "apps": {
                              'api': {
                                  "models": ["models"],
                                  "default_connection": "default",
                              }
                          },
                      },
                      generate_schemas=True)
Esempio n. 4
0
def create_app():
    fast_app = FastAPI(debug=False)
    register_tortoise(fast_app, config=TORTOISE_ORM)

    home_app = FastAPI(root_path="/")
    templates_index = Jinja2Templates(directory="front")

    @home_app.get('/')
    async def main(request: Request):
        return templates_index.TemplateResponse('index.html',
                                                {"request": request})

    home_app.mount('/', StaticFiles(directory='front'))
    fast_app.mount('/app', home_app)

    fast_app.mount("/admin", admin_app)

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

    return fast_app
Esempio n. 5
0
def get_application() -> FastAPI:
    application = FastAPI()

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

    # 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)

    # init database models
    register_tortoise(application,
                      db_url=DATABASE,
                      generate_schemas=True,
                      modules={"models": ["serv.models.images"]})

    application.include_router(api_router, prefix=API_PREFIX)

    return application
Esempio n. 6
0
def create_app():
    app = FastAPI()
    app.mount(
        "/static",
        StaticFiles(directory=os.path.join(BASE_DIR, "static")),
        name="static",
    )

    @app.get("/")
    async def index():
        return RedirectResponse(url="/admin")

    admin_app.add_exception_handler(HTTP_500_INTERNAL_SERVER_ERROR, server_error_exception)
    admin_app.add_exception_handler(HTTP_404_NOT_FOUND, not_found_error_exception)
    admin_app.add_exception_handler(HTTP_403_FORBIDDEN, forbidden_error_exception)
    admin_app.add_exception_handler(HTTP_401_UNAUTHORIZED, unauthorized_error_exception)

    @app.on_event("startup")
    async def startup():
        redis = aioredis.from_url(
            settings.REDIS_URL,
            decode_responses=True,
            encoding="utf8",
        )
        await admin_app.configure(
            logo_url="https://preview.tabler.io/static/logo-white.svg",
            template_folders=[os.path.join(BASE_DIR, "templates")],
            favicon_url="https://raw.githubusercontent.com/fastapi-admin/fastapi-admin/dev/images/favicon.png",
            providers=[
                LoginProvider(
                    login_logo_url="https://preview.tabler.io/static/logo.svg",
                    admin_model=Admin,
                )
            ],
            redis=redis,
        )

    app.mount("/admin", admin_app)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["*"],
    )
    register_tortoise(
        app,
        config={
            "connections": {"default": settings.DATABASE_URL},
            "apps": {
                "models": {
                    "models": ["examples.models"],
                    "default_connection": "default",
                }
            },
        },
        generate_schemas=True,
    )
    return app
def init_db(app: FastAPI) -> None:
    register_tortoise(
        app,
        config=TORTOISE_ORM,
        add_exception_handlers=True,
        generate_schemas=os.environ.get("GENERATE_SCHEMAS", default=False),
    )
Esempio n. 8
0
def init_db(app: FastAPI) -> None:
    register_tortoise(
        app,
        config=TORTOISE_ORM,
        generate_schemas=False,
        add_exception_handlers=True,
    )
def _init_db(app: FastAPI):
    '''
    Initializes the database
    '''
    register_tortoise(app,
                      db_url=tortoise_settings.db_url,
                      generate_schemas=tortoise_settings.generate_schemas,
                      modules=tortoise_settings.modules)
Esempio n. 10
0
def init_db(app: FastAPI, db_url: str):
    register_tortoise(
        app,
        db_url=db_url,
        modules={"models": ["app.models.tortoise"]},
        generate_schemas=False,
        add_exception_handlers=True,
    )
Esempio n. 11
0
 def _register_models(self):
     register_tortoise(
         self.app,
         db_url="sqlite://:memory:",
         modules={"models": self.models},
         generate_schemas=True,
         add_exception_handlers=True,
     )
Esempio n. 12
0
def init_db(app: FastAPI) -> None:
    register_tortoise(
        app,
        db_url=settings.DATABASE_URL,
        modules={"models": [*settings.MODELS]},
        generate_schemas=False,
        add_exception_handlers=True,
    )
Esempio n. 13
0
def init_db(app: FastAPI) -> None:
    register_tortoise(
        app,
        db_url=config("DATABASE_URL", default="sqlite://sqlite.db"),
        modules={"models": ["app.models.tortoise"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )
Esempio n. 14
0
def init_db(app: FastAPI) -> None:
    register_tortoise(
        app,
        db_url=os.environ.get("DATABASE_URL"),
        modules={"models": ["app.models.tortoise"]},
        generate_schemas=False,
        add_exception_handlers=True,
    )
Esempio n. 15
0
def init_db(app: FastAPI, settings: BaseSettings) -> None:
    register_tortoise(
        app,
        db_url=settings.database_url,
        modules={"models": ["app.models"]},
        generate_schemas=False,
        add_exception_handlers=True,
    )
Esempio n. 16
0
def register_mysql(app: FastAPI) -> NoReturn:
    mysql = setting.mysql
    register_tortoise(
        app,
        db_url=
        f"mysql://{mysql.user}:{mysql.password}@{mysql.host}:{mysql.port}/{mysql.database}?charset=utf8mb4",
        modules={"models": ["callback.models.mysql"]},
    )
Esempio n. 17
0
def init_db(app):
    register_tortoise(
        app,
        db_url=conf.db_url(),
        modules={'models': [f'{module}.models' for module in conf.modules]},
        generate_schemas=True,
        add_exception_handlers=True
    )
Esempio n. 18
0
def db_init(app):
    register_tortoise(
        app,
        db_url=SQLALCHEMY_DATABASE_URL,
        modules={"models": ["app.models.model"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )
Esempio n. 19
0
def configure_db(app: FastAPI):
    register_tortoise(
        app,
        db_url="sqlite://db.sqlite3",
        modules={'models': ['database.models']},
        generate_schemas=True,
        add_exception_handlers=True,
    )
Esempio n. 20
0
def init_db():
    register_tortoise(
        app,
        db_url="postgres://*****:*****@localhost:5432/test_db",
        modules={'models': ['app.models']},
        generate_schemas=True,
        add_exception_handlers=True,
    )
Esempio n. 21
0
def init_db(app):
    register_tortoise(
        app,
        db_url=settings.DATABASE_URL,
        modules={"models": ["app.models.auth"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )
 async def init_connect():
     # 连接数据库
     register_tortoise(
         app,
         config=settings.DATABASE_CONFIG,
         generate_schemas=True,  # True 表示连接数据库的时候同步创建表
         add_exception_handlers=True,
     )
     logger.info("start server and register_tortoise")
Esempio n. 23
0
def init_database(app: FastAPI) -> None:
    """Initializes database connection with Tortoise."""
    register_tortoise(
        app=app,
        db_url=DATABASE_URL,
        modules={"models": APP_MODELS},
        generate_schemas=False,
        add_exception_handlers=True,
    )
Esempio n. 24
0
File: app.py Progetto: socylx/tifa
def setup_db_models(app):
    m = import_submodules("tifa.models")
    register_tortoise(
        app,
        db_url=get_settings().POSTGRES_DATABASE_URI,
        modules={
            "models": ["tifa.models"],
        },
    )
Esempio n. 25
0
def init_db(app: FastAPI) -> None:
    """Register Tortoise ORM."""
    register_tortoise(
        app=app,
        db_url=get_settings().database_url,
        modules={'models': ['app.models']},
        generate_schemas=False,
        add_exception_handlers=True,
    )
Esempio n. 26
0
File: db.py Progetto: rvaccari/sbgo
def init_db(app: FastAPI) -> None:
    settings = get_settings()
    register_tortoise(
        app,
        db_url=settings.database_url,
        modules=settings.modules,
        generate_schemas=True,
        add_exception_handlers=True,
    )
Esempio n. 27
0
def client() -> Generator:
    register_tortoise(
        app,
        db_url="sqlite://:memory:",
        modules={"models": ["neobee_relay.models.board", "neobee_relay.models.measure"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )
    with TestClient(app) as c:
        yield c
Esempio n. 28
0
async def startup():
    register_tortoise(
        api,
        modules={"models": ["gram.models"]},
        db_url=db_connection_string(),
        generate_schemas=True,
        add_exception_handlers=True,
    )
    redis = await create_redis_pool(redis_connection_string())
    FastAPILimiter.init(redis)
def register_db(app: FastAPI, db_url: str = None):
    db_url = db_url or settings.DB_URL
    app_list = get_app_list()
    register_tortoise(
        app,
        db_url=db_url,
        modules={"models": app_list},
        generate_schemas=True,
        add_exception_handlers=True,
    )
Esempio n. 30
0
def init_db(app: FastAPI):
    """
    Init database models.
    :param app:
    :return:
    """
    register_tortoise(
        app=app,
        config=TORTOISE_ORM,
    )