Exemplo n.º 1
0
def initialize_database(database_url=None):
    global engine, Session
    from alvinchow_backend.db import functions  # noqa

    database_url = database_url or config.DATABASE_URL

    connection_args = {'connect_args': {'connect_timeout': 10}}

    if config.DEBUG_SQL:
        connection_args.update({'echo': True})

    engine = create_engine(database_url, **connection_args)
    session_factory = sessionmaker(bind=engine)
    Session = scoped_session(session_factory)

    # import models to register them here
    from alvinchow_backend.db import models  # noqa
    from sqlalchemy_bigint_id import setup_bigint_id_for_all_tables

    functions.register_postgres_functions(metadata=Base.metadata)

    # Register bigid for all tables that have it
    setup_bigint_id_for_all_tables(metadata=Base.metadata)

    instrument_sqlalchemy(engine)
def conn_with_scout():
    """
    Create an instrumented SQLAlchemy connection to an in-memory SQLite database.

    """
    engine = create_engine("sqlite:///:memory:")
    instrument_sqlalchemy(engine)
    conn = engine.connect()
    try:
        yield conn
    finally:
        conn.close()
def init_db() -> None:
    """ Initialize database connections based on config """
    from .config import get_config

    global SessionLocal, engine

    _config = get_config()
    sqlalchemy_database_url = _config["database_url"]

    connect_args = {}
    if get_config()["env"] != "local":  # pragma: no cover
        # Use SSL to connect to databases
        _ca_pem_path = Path(__file__).parent / "rds-ca-2019-root.pem"
        connect_args = {"ssl": {"ca": str(_ca_pem_path.absolute())}}

    engine = create_engine(sqlalchemy_database_url, connect_args=connect_args, pool_pre_ping=True)
    Base.metadata.bind = engine
    SessionLocal = sessionmaker(autoflush=False, bind=engine)

    if _config.get("scout"):  # pragma: no cover
        from scout_apm.sqlalchemy import instrument_sqlalchemy

        instrument_sqlalchemy(engine)
def test_instrument_engine_is_idempotent():
    engine = create_engine("sqlite:///:memory:")
    instrument_sqlalchemy(engine)
    instrument_sqlalchemy(engine)  # does nothing, doesn't crash
Exemplo n.º 5
0
import asyncio
import logging
import os

import uvicorn
from scout_apm.api import Config, instrument
from scout_apm.async_.starlette import ScoutMiddleware
from scout_apm.sqlalchemy import instrument_sqlalchemy
from fastapi import BackgroundTasks, FastAPI, Depends
from sqlalchemy.orm import Session
from database import SessionLocal, engine, User, Base
from database_async import database, users, engine as async_engine

Base.metadata.create_all(bind=engine)
instrument_sqlalchemy(engine)
# instrument_sqlalchemy(async_engine)

app = FastAPI()


# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# @app.on_event("startup")
async def startup():