示例#1
0
def setup_app(app: FastAPI):
    """
    Настройка приложения
    """

    # Шаблон для задания структуры базы данных
    TRAFARET = T.Dict({
        T.Key('databases'):
        T.List(
            T.Dict({
                'name':
                T.String(),
                'address':
                T.String(),
                'collections':
                T.List(
                    T.Dict({
                        'name':
                        T.String(),
                        'fields':
                        T.List(T.String),
                        T.Key('index_fields', optional=True):
                        T.List(T.String),
                    }))
            }))
    })

    config = read_and_validate('config.yaml', TRAFARET)
    app.config = config

    app.add_middleware(CheckUserAuthMiddleware)
示例#2
0
def create_app(config: Config):
    app = FastAPI(openapi_url="/openapi/spec.json",
                  docs_url="/swagger",
                  redoc_url="/redoc",
                  debug=True)
    app.include_router(router)

    # wire things up
    app.config = Config()
    app.session = SessionWrapper(s=Session())
    app.db = DB(app.config.DB_DSN.get_secret_value())
    app.repositories = lambda: None
    app.repositories.zipcodes = ZipCodeRepository(db=app.db)
    app.shutdown = lambda: __import__('os').kill(app.config.PID,
                                                 __import__('signal').SIGTERM)

    @app.on_event("startup")
    async def setup() -> None:
        logging.info(f"[APP_SETUP] {app} {app.config}")

        app.loop = asyncio.get_running_loop()
        await app.db.setup(app)
        await app.session.s.setup()

    @app.on_event("shutdown")
    async def teardown() -> None:
        logging.info(f"[APP_TEARDOWN] {app} {app.config}")

        await app.session.s.teardown()
        await app.db.teardown()

    return app
def create_app() -> FastAPI:
    app = FastAPI(title="secret transferring service")
    app.include_router(api_router)
    app.config = Settings()  # type: ignore
    app.router.add_event_handler("startup", create_redis(app))
    app.router.add_event_handler("shutdown", shutdown_redis(app))

    return app
def create_fastapi_app():
    app = FastAPI()
    app.debug = True
    app.testing = True
    app.secret_key = "testing"
    app.test_client = TestClient(app)
    app.config = {
        "OAUTH2_ERROR_URIS":
        [("invalid_client", "https://a.b/e#invalid_client")]
    }
    return app
示例#5
0
def create_api():
    """Create the API."""
    config = configuration.from_envvar()
    app = FastAPI(
        title=config["API_NAME"],
        version=config["VERSION"],
        openapi_url=f'{config["API_PREFIX"]}/{config["OPENAPI_URL"]}',
        docs_url=f'{config["API_PREFIX"]}/{config["DOCS_URL"]}',
        redoc_url=f'{config["API_PREFIX"]}/{config["REDOC_URL"]}',
    )
    app.config = config

    setup_logger(app, log_name="api")
    setup_routes(app)

    return app
示例#6
0
def create_app():
    """App factory."""
    config = configuration.from_envvar()
    app = FastAPI(
        title=config["API_NAME"],
        version=config["VERSION"],
        openapi_url=f'{config["API_PREFIX"]}/{config["OPENAPI_URL"]}',
        docs_url=f'{config["API_PREFIX"]}/{config["DOCS_URL"]}',
        redoc_url=f'{config["API_PREFIX"]}/{config["REDOC_URL"]}',
    )
    app.config = config

    setup_requests(app)
    setup_logger(app)
    setup_redis(app)
    setup_routes(app)

    return app
示例#7
0
def create_app():

    app = FastAPI(
        title='TDCTL-API',
        version=0.1,
        description='''TDCTL-database API. 
        Everything related to Tromsøstudentenes Dataforening''',
        contact={
            'name': 'td',
            'email': '*****@*****.**'
        },
        docs_url="/",
    )

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

    # Routers
    app.include_router(members.router, prefix="/api/member", tags=['members'])
    app.include_router(auth.router, prefix="/api/auth", tags=['auth'])
    app.include_router(events.router, prefix="/api/event", tags=['event'])
    app.include_router(eventPost.router,
                       prefix="/api/event",
                       tags=['event post'])

    # Fetch config object
    env = os.getenv('FLASK_APP_ENV', 'default')
    app.config = config[env]

    setup_db(app)
    # Set tokens to expire at at "exp"
    app.db.tokens.create_index("exp", expireAfterSeconds=0)

    return app
示例#8
0
def create_app() -> FastAPI:
    #定义app对象
    app = FastAPI()  #FastAPI(title='CustomLogger', debug=False)
    app.config = fs_config

    #init config
    logger = CustomizeLogger.make_logger(app.config)
    app.logger = logger

    #注册路由
    app.include_router(user_router)
    app.include_router(socker_router)

    #测试路由
    app.include_router(test_router)
    app.include_router(task_router)

    app.include_router(files_router)

    #init db
    app.database = database
    return app
示例#9
0
def make_app(
        config_path: Path,
        version: str,
        endpoints: List[Endpoint],
        enable_middlewares: List[str],
        additional_middlewares: list,
) -> FastAPI:
    """Create app with endpoints and middlewares.

    App is configured using the config of the service and defined
    environment-variables.
    Also logger is configured and default endpoints and additional endpoints
    added.
    Same for middlewares.

    Note:
        An app created by this function has additional attributes:

        * ``app.logger``
        * ``app.config``
        * ``app.databases``
        * ``app.services``
        * ``app.mode``

    Parameters:
        config_path: the path for the config file to use for the app.
        version: current version of the service, should be ``__version__``
            variable inside the module ``app`` of your service.
        endpoints: the endpoints to include to the app.
        enable_middlewares: list of the middlewares to add.
        additional_middlewares: list of non default middlewares to add to the
            app.

    Returns:
        the created app.

    """
    # load the config and environment-variables for the service and
    # combine these information to initialize the app
    config = collect_config_definition(config_path=config_path)

    # update mode and logger-definitions with environment-variables if defined
    # ATTENTION: the environment-variable has the prefix of the servicename
    config = update_config(
        env_vars=config.available_environment_variables.env_vars,
        external_resources_env_vars=(
            config.available_environment_variables.external_resources_env_vars
        ),
        rules_env_vars=config.available_environment_variables.rules_env_vars,
        config=config,
        model=Config,
    )

    # convert config-attribute types if necessary
    config.logger.path = Path(config.logger.path)
    config.service.readme = Path(config.service.readme)

    # initialize the app, add combined configuration, mode and logger
    app = FastAPI(
        title=f'{config.service.name} [{config.service.mode.upper()}]',
        description=config.service.readme.read_text(),
        version=version,
    )

    # add additional attributes to the app like the config and the runtime-mode
    app.config = config
    app.mode = config.service.mode

    # Set the logging-configuration
    app.logger = customize_logging(
        config.logger.path / config.logger.filename.format(mode=app.mode),
        level=config.logger.level,
        retention=config.logger.retention,
        rotation=config.logger.rotation,
        _format=config.logger.format
    )

    # if dependencies for external databases are defined in the config, add
    # these database-definitions to the app
    if config.external_resources.databases:
        app = add_databases_to_app(
            app,
            dbs=config.external_resources.databases
        )
    else:
        app.databases = {}

    # if dependencies for external services are defined in the config, add
    # these service-definitions to the app
    if config.external_resources.services:
        app = add_services_to_app(
            app,
            services=config.external_resources.services
        )
    else:
        app.services = {}

    # add default endpoints if defined in the config
    endpoints = add_default_endpoints(endpoints=endpoints, config=app.config)

    # include defined routers and middlewares to the app
    return include_endpoints_and_middlewares_to_app(
        app=app,
        endpoints=endpoints,
        enable_middlewares=enable_middlewares,
        additional_middlewares=additional_middlewares
    )
示例#10
0
from mangum import Mangum
from starlette.exceptions import HTTPException as StarletteHTTPException
from src.routes import router
from src.database import Base, engine
from src.oauth2 import config_oauth

app = FastAPI()

app.config = {
    'OAUTH2_JWT_ISS':
    'https://authlib.org',
    'OAUTH2_JWT_KEY':
    'secret-key',
    'OAUTH2_JWT_ALG':
    'HS256',
    'OAUTH2_TOKEN_EXPIRES_IN': {
        'authorization_code': 300
    },
    'OAUTH2_ERROR_URIS': [
        ('invalid_client',
         'https://developer.your-company.com/errors#invalid-client'),
    ]
}


@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    '''Override the StarletteHTTPException exception'''
    return JSONResponse(status_code=exc.status_code, content=exc.detail)

示例#11
0
import os
import sys

from fastapi import FastAPI
import uvicorn

path = os.path.dirname(os.path.abspath(__file__))  # NOQA
sys.path.append(path)  # NOQA

# Configuration
from config import Config

# Initialize App
app = FastAPI()
app.config = Config().dict()

from controller.classify_text import *
# For run debugger
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=False)
示例#12
0
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from starlette.status import HTTP_401_UNAUTHORIZED
from pydantic import BaseModel
import sqlite3
import hashlib
import os
from dotenv import dotenv_values
import random
from hashlib import sha256
from os import environ
app = FastAPI()
security = HTTPBasic()

app.secret_key = os.getenv("SECRET")
if "SECRET" not in os.environ:
    app.config = dotenv_values(".env")
    app.secret_key = app.config['SECRET']

app.session_token = ''


@app.get("/")
def root():
    return {"message": "Welcome"}


class ContentRequest(BaseModel):
    content: str


@app.on_event("startup")