Exemplo n.º 1
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
Exemplo n.º 2
0
def get_app() -> FastAPI:
    app_settings = load_config()
    title = app_settings[ConfigSections.DEFAULT][DefaultSectionKeys.NAME]
    version = app_settings[ConfigSections.DEFAULT][DefaultSectionKeys.VERSION]
    api_prefix = app_settings[ConfigSections.DEFAULT][
        DefaultSectionKeys.API_PREFIX]
    conn_string = app_settings[ConfigSections.DEFAULT][
        DefaultSectionKeys.CACHE_CONNECTION_STRING]
    db = DbEngine(conn_string)

    server = FastAPI(
        title=title,
        version=version,
    )

    server.db = db

    health.router.version = server.version
    health.router.title = server.title
    health.router.db = db
    server.include_router(health.router, )

    users.router.db = db
    server.include_router(users.router,
                          #prefix=api_prefix,
                          )

    most_frequent.router.db = db
    server.include_router(most_frequent.router,
                          #prefix=api_prefix,
                          )

    logger.info('****************** Starting Server *****************')
    return server
Exemplo n.º 3
0
def create_app() -> FastAPI:
    """Create a fastapi instance that has logging and database set up

    remove app config from main.py to keep main clean. static routes aren't added
    here because if you try to add things to the root level (i.e. favicons) here,
    you'll block every other app.route since the resolver looks top -> bottom

    Returns
    -------
    new_app : FastAPI
        app with logger and db attached
    """
    new_app = FastAPI(title="WikiMap", version="0.0.2", debug=False)
    new_app.logger = get_logging_config()
    new_app.db = get_database()
    return new_app
Exemplo n.º 4
0

MONGO_HOST = os.environ.get('MONGO_HOST', 'database')
MONGO_PORT = os.environ.get('MONGO_PORT', 27017)
MONGO_PASSWORD = os.environ.get('MONGO_PASSWORD', 'secret')
MONGO_USER = os.environ.get('MONGO_USER', 'mongo')

app = FastAPI()

client = AsyncIOMotorClient(f"mongodb://{MONGO_HOST}:{MONGO_PORT}",
                            username=MONGO_USER,
                            password=MONGO_PASSWORD,
                            authSource='mlDatabase',
                            authMechanism='SCRAM-SHA-256')

app.db = client.mlDatabase

origins = [
    "http://localhost", "http://localhost:8000", "http://localhost:4200",
    "http://localhost:4201", "http://127.0.0.1:4201", "http://127.0.0.1:4200"
]

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

Exemplo n.º 5
0
<title>Shorty</title>
<meta name="description" value="A self-hosted link shortener and vanity provider."/>
<meta name="theme-color" value="#ffd866"/>
</head>
<body>
<h1>Uh?</h1>
<p>Our systems detected that you're a bot, and uh, we don't allow bots. If you're not a bot, then that sucks.</p>
<p>If you are a bot, go away.</p>
<p>With love, dragdev studios</p>
</body>
</html>
"""
EMBED_RESPONSE = HTMLResponse(EMBED_DATA, 200)

app = FastAPI(title="Shorty", description="Self-hosted link shortener that also serves as a vanity link provider.")
app.db = None
limits = buckets
ratelimits = {
    "/s": [10, 300],
}


@app.middleware("http")
async def handle_ratelimit(request: Request, call_next):
    ip = request.client.host
    route = request.url.path
    for p in ratelimits.keys():
        if fnmatch(route, p):
            if ip not in buckets.keys():
                buckets[ip] = {}
            if p not in buckets[ip].keys():