How to use the sqlalchemy.create_engine function in SQLAlchemy

To help you get started, we’ve selected a few SQLAlchemy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Flexget / Flexget / flexget / manager.py View on Github external
self.db_filename = db_test_filename
                # Different database, different lock file
                self.lockfile = os.path.join(self.config_base, '.test-%s-lock' % self.config_name)
                log.info('Test database created')

            # in case running on windows, needs double \\
            filename = self.db_filename.replace('\\', '\\\\')
            self.database_uri = 'sqlite:///%s' % filename

        if self.db_filename and not os.path.exists(self.db_filename):
            log.verbose('Creating new database %s ...' % self.db_filename)

        # fire up the engine
        log.debug('Connecting to: %s' % self.database_uri)
        try:
            self.engine = sqlalchemy.create_engine(self.database_uri,
                                                   echo=self.options.debug_sql,
                                                   poolclass=SingletonThreadPool,
                                                   connect_args={'check_same_thread': False})  # assert_unicode=True
        except ImportError:
            print('FATAL: Unable to use SQLite. Are you running Python 2.5 - 2.7 ?\n'
                  'Python should normally have SQLite support built in.\n'
                  'If you\'re running correct version of Python then it is not equipped with SQLite.\n'
                  'You can try installing `pysqlite`. If you have compiled python yourself, '
                  'recompile it with SQLite support.', file=sys.stderr)
            sys.exit(1)
        Session.configure(bind=self.engine)
        # create all tables, doesn't do anything to existing tables
        try:
            def before_table_create(event, target, bind, tables=None, **kw):
                if tables:
                    # We need to acquire a lock if we are creating new tables
github mikeckennedy / python-for-entrepreneurs-course-demos / 12_user_accounts / blue_yellow_app_12 / blue_yellow_app / data / dbsession.py View on Github external
def global_init(db_file):
        if DbSessionFactory.factory:
            return

        if not db_file or not db_file.strip():
            raise Exception("You must specify a data file.")

        conn_str = 'sqlite:///' + db_file
        print("Connecting to db with conn string: {}".format(conn_str))

        engine = sqlalchemy.create_engine(conn_str, echo=False)
        SqlAlchemyBase.metadata.create_all(engine)
        DbSessionFactory.factory = sqlalchemy.orm.sessionmaker(bind=engine)
github wikimedia / analytics-wikimetrics / database_migrations / env.py View on Github external
def get_engine(config, url_field='WIKIMETRICS_ENGINE_URL'):
    """
    Create a sqlalchemy engine for a database.

    Returns:
        sqlalchemy engine connected to the database.
    """

    return create_engine(
        config[url_field],
        echo=config['SQL_ECHO'],
        connect_args={"charset" : "utf8"},
        # pool_size=config['WIKIMETRICS_POOL_SIZE'],
        poolclass=NullPool,
    )
github dimmg / flusk / core / api / common / database.py View on Github external
import os

from sqlalchemy import create_engine
from sqlalchemy.exc import DatabaseError
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy_utils import database_exists, create_database, drop_database


engine = create_engine(os.environ.get(
    'SQLALCHEMY_DATABASE_URI'), convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))


class CustomBase(object):
    """This overrides the default
    `_declarative_constructor` constructor.
    It skips the attributes that are not present
    for the model, thus if a dict is passed with some
    unknown attributes for the model on creation,
    it won't complain for `unkwnown field`s.
    """
    def __init__(self, **kwargs):
        cls_ = type(self)
github openstack / glance / glance / openstack / common / db / sqlalchemy / provision.py View on Github external
def get_engine(uri):
    """Engine creation

    Call the function without arguments to get admin connection. Admin
    connection required to create temporary user and database for each
    particular test. Otherwise use existing connection to recreate connection
    to the temporary database.
    """
    return sqlalchemy.create_engine(uri, poolclass=sqlalchemy.pool.NullPool)
github riotkit-org / file-repository / kropot-cli / src / kropotcli / persistance.py View on Github external
def __init__(self, db_string: str):
        Logger.info('ORM is initializing')
        self.engine = create_engine(db_string, echo=False)
        self.session = sessionmaker(bind=self.engine, autoflush=False, autocommit=True)()
        Base.metadata.create_all(self.engine)
github RasaHQ / rasa / rasa / core / tracker_store.py View on Github external
) -> None:
        import sqlalchemy
        from sqlalchemy.orm import sessionmaker
        from sqlalchemy import create_engine

        engine_url = self.get_db_url(
            dialect, host, port, db, username, password, login_db
        )
        logger.debug(
            "Attempting to connect to database " 'via "{}"'.format(repr(engine_url))
        )

        # Database might take a while to come up
        while True:
            try:
                self.engine = create_engine(engine_url)

                # if `login_db` has been provided, use current connection with
                # that database to create working database `db`
                if login_db:
                    self._create_database_and_update_engine(db, engine_url)

                try:
                    self.Base.metadata.create_all(self.engine)
                except (
                    sqlalchemy.exc.OperationalError,
                    sqlalchemy.exc.ProgrammingError,
                ) as e:
                    # Several Rasa services started in parallel may attempt to
                    # create tables at the same time. That is okay so long as
                    # the first services finishes the table creation.
                    logger.error("Could not create tables: {}".format(e))
github bandprotocol / band / stat-server / dump.py View on Github external
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (
    create_engine,
    Column,
    Integer,
    String,
    ForeignKey,
    JSON,
    BigInteger,
    Index,
)
from sqlalchemy.orm import sessionmaker

from config import DATABASE_URI

engine = create_engine(DATABASE_URI)
Session = sessionmaker(bind=engine)
session = Session()

Base = declarative_base()


class Request(Base):
    __tablename__ = "request"
    id = Column(BigInteger, primary_key=True)
    ip = Column(String, nullable=False)
    tcd_address = Column(String, nullable=False)
    key = Column(String, nullable=False)
    status = Column(String)
    value = Column(String)
    timestamp = Column(Integer)
    requested_at = Column(Integer, index=True)
github fedora-python / portingdb / scripts / check-specs.py View on Github external
def get_portingdb(db):
    """Return session object for portingdb."""
    url = 'sqlite:///' + db
    engine = create_engine(url)
    return get_db(None, engine=engine)
github Ericsson / codechecker / libcodechecker / database_handler.py View on Github external
def create_engine(connection_string):
        """
        Creates a new SQLAlchemy engine.
        """

        if make_url(connection_string).drivername == 'sqlite+pysqlite':
            # FIXME: workaround for locking errors
            return sqlalchemy.create_engine(
                connection_string,
                encoding='utf8',
                connect_args={'timeout': 600})
        else:
            return sqlalchemy.create_engine(connection_string,
                                            encoding='utf8')