def setup_db(app: Flask, create_all: bool = False): """ Initialize our database connection. """ app.config["SQLALCHEMY_ECHO"] = True if os.getenv("DB_DEBUG") else False app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False conn_uri = get_db_conn_uri_from_env() app.config["SQLALCHEMY_DATABASE_URI"] = conn_uri app.config["SQLALCHEMY_BINDS"] = { 'dashboard_service': conn_uri, 'experiment_service': conn_uri, 'auth_service': conn_uri, 'api_service': conn_uri } # let sqlalchemy utils help us converting data in/out of the database force_auto_coercion() # when running SQLite, we must enable this directive on each new # connexion made to the database to enable foreign key relationships if conn_uri.startswith("sqlite"): @event.listens_for(Engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() with app.app_context(): db.init_app(app) if create_all: db.create_all(app=app)
def init_db(_app: Flask) -> None: """ DBの初期化・マイグレーション """ force_auto_coercion() db.init_app(_app) Migrate(_app, db)
def register_models(app: Flask) -> Flask: from sqlalchemy_utils import force_auto_coercion force_auto_coercion() from . import models app.models = models return app
def init_db(app=None, db=None): """Initializes the global database object used by the app.""" if isinstance(app, Flask) and isinstance(db, SQLAlchemy): force_auto_coercion() load_models() db.init_app(app) else: raise ValueError('Cannot init DB without db and app objects.')
def register_extensions(app): sqlalchemy_utils.force_instant_defaults() sqlalchemy_utils.force_auto_coercion() DB.init_app(app) CORS.init_app(app) MIGRATE.init_app(app, DB) SOCKETIO.init_app(app) JWT.init_app(app) JWT._set_error_handler_callbacks(REST)
def init_app(db: types.MyDb, app: Flask) -> None: """Initialize the given app and the given db. :param db: The db to initialize. This function adds some listeners to some queries. :param app: The app to initialize with. :returns: Nothing, everything will be mutated in-place. """ db.init_app(app) force_auto_coercion() with app.app_context(): @app.before_request def __set_query_durations() -> None: g.queries_amount = 0 g.queries_total_duration = 0 g.queries_max_duration = None g.query_start = None @event.listens_for(db.engine, "before_cursor_execute") def __before_cursor_execute(*_args: object) -> None: if hasattr(g, 'query_start'): g.query_start = datetime.datetime.utcnow() @event.listens_for(db.engine, "after_cursor_execute") def __after_cursor_execute(*_args: object) -> None: if hasattr(g, 'queries_amount'): g.queries_amount += 1 if hasattr(g, 'query_start'): delta = (datetime.datetime.utcnow() - g.query_start).total_seconds() if hasattr(g, 'queries_total_duration'): g.queries_total_duration += delta if ( hasattr(g, 'queries_max_duration') and ( g.queries_max_duration is None or delta > g.queries_max_duration ) ): g.queries_max_duration = delta if app.config.get('_USING_SQLITE'): # pragma: no cover @event.listens_for(db.engine, "connect") def __do_connect(dbapi_connection: t.Any, _: t.Any) -> None: # disable pysqlite's emitting of the BEGIN statement entirely. # also stops it from emitting COMMIT before any DDL. dbapi_connection.isolation_level = None dbapi_connection.execute('pragma foreign_keys=ON') @event.listens_for(db.engine, "begin") def __do_begin(conn: t.Any) -> None: # emit our own BEGIN conn.execute("BEGIN")
def init_db(app=None, db=None): """ Initializes the global database object used by the app. Code base courtesy of: https://bobwaycott.com/blog/how-i-use-flask/organizing-flask-models-with-automatic-discovery/ """ if isinstance(app, Flask) and isinstance(db, SQLAlchemy): force_auto_coercion() load_models() database_uri = make_db_uri(app) app.config["SQLALCHEMY_DATABASE_URI"] = database_uri app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.app = app db.init_app(app) migrate.init_app(app, db) log.info(f'Database Successfully configured.') else: raise ValueError('Cannot init DB without db and app objects.')
def init_app(db: types.MyDb, app: Flask) -> None: """Initialize the given app and the given db. :param db: The db to initialize. This function adds some listeners to some queries. :param app: The app to initialize with. :returns: Nothing, everything will be mutated in-place. """ db.init_app(app) force_auto_coercion() with app.app_context(): @app.before_request def __set_query_durations() -> None: g.queries_amount = 0 g.queries_total_duration = 0 g.queries_max_duration = None g.query_start = None @event.listens_for(db.engine, "before_cursor_execute") def __before_cursor_execute(*_args: object) -> None: if hasattr(g, 'query_start'): g.query_start = time.time() @event.listens_for(db.engine, "after_cursor_execute") def __after_cursor_execute(*_args: object) -> None: if hasattr(g, 'queries_amount'): g.queries_amount += 1 if hasattr(g, 'query_start'): delta = time.time() - g.query_start if hasattr(g, 'queries_total_duration'): g.queries_total_duration += delta if (hasattr(g, 'queries_max_duration') and (g.queries_max_duration is None or delta > g.queries_max_duration)): g.queries_max_duration = delta
# | This program is distributed in the hope that it will be useful, | # | but WITHOUT ANY WARRANTY; without even the implied warranty of | # | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | # | GNU General Public License for more details. | # | | # | You should have received a copy of the GNU General Public License | # | along with this program. If not, see <http://www.gnu.org/licenses/>. | # +---------------------------------------------------------------------------+ from flask_cors import CORS import logging logging.getLogger('flask_cors').level = logging.DEBUG cross_origin_resource_sharing = CORS() from sqlalchemy_utils import force_auto_coercion, force_instant_defaults force_auto_coercion() force_instant_defaults() from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from . import api from . import projects def init_app(app): """ Application extensions initialization. """ EXTENSIONS = (cross_origin_resource_sharing, api, projects, db)
from steerclear import db from flask.ext import login from sqlalchemy_utils.types.phone_number import PhoneNumberType from sqlalchemy_utils import force_auto_coercion # This is needed so that if we create a User object # by passing it a string as a phone number, it will # coerce the string to a phone number object force_auto_coercion() class Role(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __repr__(self): return "Role(ID %r, Name %r, Description %r" % ( self.id, self.name, self.description ) class User(db.Model, login.UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(120), unique=True) phone = db.Column(PhoneNumberType, unique=True) rides = db.relationship('Ride', backref='user', lazy='dynamic') roles = db.relationship('Role', backref='user', lazy='dynamic')
def import_models(): force_auto_coercion() __import__('db.models', fromlist=['*'])
from ekklesia_common.lid import LID from ekklesia_common.psycopg2_debug import make_debug_connection_factory rel = relationship FK = ForeignKey C = Column Table = Table bref = backref SLOW_QUERY_SECONDS = 0.3 sqllog = logging.getLogger("sqllog") Session = scoped_session(sessionmaker()) sqlalchemy_utils.force_auto_coercion() # Taken from https://alembic.sqlalchemy.org/en/latest/naming.html meta = MetaData( naming_convention={ "ix": "ix_%(column_0_label)s", "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(constraint_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s" }) Base = declarative_base(metadata=meta) db_metadata = Base.metadata
import arrow import logging import sqlalchemy_utils as sau from flask import url_for from app import ( db, login_manager, ) sau.force_auto_coercion() logger = logging.getLogger(__name__) class Model(db.Model): __abstract__ = True class TimestampMixin(object): created_at = db.Column(sau.ArrowType(), index=True, default=arrow.utcnow) updated_at = db.Column(sau.ArrowType(), index=True, default=arrow.utcnow, onupdate=arrow.utcnow) class User(TimestampMixin, Model): __tablename__ = 'user'