sqlalchemy.orm.sessionmaker

Here are the examples of the python api sqlalchemy.orm.sessionmaker taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

699 Examples 7

3 Source : sql.py
with GNU General Public License v3.0
from Aadhi000

def start() -> scoped_session:
    engine = create_engine(DB_URI, client_encoding="utf8")
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=False))


BASE = declarative_base()

3 Source : __init__.py
with GNU General Public License v3.0
from AASFCYBERKING

def start() -> scoped_session:
    engine = create_engine(DB_URL, client_encoding="utf8")
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=True))


BASE = declarative_base()

3 Source : sqlite.py
with GNU General Public License v3.0
from abhinavthomas

    def __init__(self):
        try:
            SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_PATH}"
            engine = create_engine(
                SQLALCHEMY_DATABASE_URL
            )
            self.sessionLocal = sessionmaker(
                autocommit=False, autoflush=False, bind=engine)
        except Exception as err:
            logger.error(err)

    def __exec(self, query):

3 Source : client.py
with MIT License
from aiguofer

    def create_session(self, **kwargs):
        """This is a wrapper around :any:`sqlalchemy.orm.session.sessionmaker` using
        current ``Engine`` as bind.

        Docstring for :any:`sqlalchemy.orm.session.sessionmaker`:
        """
        return sessionmaker(bind=self, **kwargs)()

    @contextmanager

3 Source : database.py
with MIT License
from Ailitonia

    def __init__(self):
        # expire_on_commit=False will prevent attributes from being expired
        # after commit.
        self.__async_session = sessionmaker(
            engine, expire_on_commit=False, class_=AsyncSession
        )

    def get_async_session(self):

3 Source : storage_impl_db.py
with Apache License 2.0
from airshipit

    def _get_session(self):
        """Lazy initilize the sessionmaker, invoke the engine getter, and
        use it to return a session
        """
        if not self._session:
            self._session = sessionmaker(bind=self._engine_getter())
        return self._session()

    @contextmanager

3 Source : events.py
with MIT License
from aliev

async def create_sqlalchemy_connection():
    # NOTE: https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#using-multiple-asyncio-event-loops
    engine = create_async_engine(settings.PSQL_DSN, echo=True, poolclass=NullPool)
    async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
    sqlalchemy.sqlalchemy_session = async_session()


async def close_sqlalchemy_connection():

3 Source : __init__.py
with MIT License
from Amberyt

def start() -> scoped_session:
    engine = create_engine(Var.DB_URI)
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=False))


try:

3 Source : __init__.py
with GNU General Public License v3.0
from AmineSoukara

def start() -> scoped_session:
    engine = create_engine(Config.DATABASE_URL)
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=False))


try:

3 Source : example_announcement_client.py
with Apache License 2.0
from amundsen-io

    def get_posts(self) -> Announcements:
        """
        Returns an instance of amundsen_application.models.announcements.Announcements, which should match
        amundsen_application.models.announcements.AnnouncementsSchema
        """
        session = sessionmaker(bind=self.engine)()

        posts = []

        for row in session.query(DBAnnouncement).order_by(DBAnnouncement.date.desc()):
            post = Post(title=row.title,
                        date=row.date.strftime('%b %d %Y %H:%M:%S'),
                        html_content=row.content)
            posts.append(post)

        return Announcements(posts)

3 Source : rds_client.py
with Apache License 2.0
from amundsen-io

    def __init__(self, sql_alchemy_url: str, client_kwargs: Dict = dict()) -> None:
        self.sql_alchemy_url = sql_alchemy_url
        self.engine = create_engine(sql_alchemy_url, **client_kwargs)
        self.session_factory = sessionmaker(bind=self.engine)

    def init_db(self) -> None:

3 Source : database.py
with MIT License
from AMZ-Driverless

    def init(config=None, debug=False):
        db_url = {'drivername': 'postgres',
                  'username': os.getenv('RBB_DB_USER') if os.getenv('RBB_DB_USER') else 'postgres',
                  'password': os.getenv('RBB_DB_PASS') if os.getenv('RBB_DB_PASS') else 'postgres',
                  'host': os.getenv('RBB_DB_HOST') if os.getenv('RBB_DB_HOST') else 'localhost',
                  'port': os.getenv('RBB_DB_PORT') if os.getenv('RBB_DB_PORT') else 5432,
                  'database': os.getenv('RBB_DB_DB') if os.getenv('RBB_DB_DB') else 'postgres'}

        Database._engine = create_engine(engine_url.URL(**db_url), echo=debug, convert_unicode=True)
        db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=Database._engine))

        Base.query = db_session.query_property()
        Database._session = db_session

3 Source : session.py
with Apache License 2.0
from analyseether

    def db_session_scope(self):
        DBSession = sessionmaker(bind=self.db_engine)
        self.db_session = DBSession()

        try:
            yield self.db_session
            # logger.debug("New data {}".format(self.db_session.new))
            # logger.debug("Updated data {}".format(self.db_session.dirty))
            self.db_session.commit()
        except Exception as e:
            self.db_session.rollback()
            raise e
        finally:
            self.db_session.close()

    def setup_filters(self):

3 Source : sql.py
with Apache License 2.0
from andrewyates

    def __init__(self, url):
        engine = sa.create_engine(url, pool_pre_ping=True)
        if not database_exists(engine.url):
            print("creating missing DB")
            create_database(engine.url)

        Base.metadata.create_all(engine)

        self.sessionmaker = sessionmaker(bind=engine)

    def queue_run(self, command, config, priority=0):

3 Source : session.py
with MIT License
from AngelLiang

    def create_session(self, dburi, short_lived_sessions=False, **kwargs):
        engine = self.get_engine(dburi, **kwargs)
        if self.forked:
            if short_lived_sessions or dburi not in self._sessions:
                self._sessions[dburi] = sessionmaker(bind=engine)
            return engine, self._sessions[dburi]
        else:
            return engine, sessionmaker(bind=engine)

    def prepare_models(self, engine):

3 Source : ib_mysql.py
with MIT License
from antx-code

    def __init__(self):
        self.engine = create_engine(f'mysql+pymysql://{MYSQL_USERNAME}:{MYSQL_PASSWD}@{MYSQL_ADDRESS}:{MYSQL_PORT}/{MYSQL_DB}')
        DbSession = sessionmaker(bind=self.engine)
        self.session = DbSession()

    @logger.catch(level='ERROR')

3 Source : config.py
with MIT License
from architus

def get_session():
    logger.debug("creating a new db session")
    Session = sessionmaker(bind=engine)
    return Session()


class AsyncConnWrapper:

3 Source : extractor.py
with Apache License 2.0
from arkhn

    def __init__(self, credentials, chunksize=None):
        if credentials is None:
            credentials = fhirpipe.global_config["source"]
        db_string = self.build_db_url(credentials)

        self.engine = create_engine(db_string)
        self.metadata = MetaData(bind=self.engine)
        self.session = sessionmaker(self.engine)()

        self.chunksize = chunksize

    @staticmethod

3 Source : database_explorer.py
with Apache License 2.0
from arkhn

def session_scope(explorer):
    """Provide a scope for sqlalchemy sessions."""
    session = sessionmaker(explorer._sql_engine)()
    try:
        yield session
    finally:
        session.close()


class DatabaseExplorer:

3 Source : conftest.py
with MIT License
from art1415926535

def session():
    db = create_engine('sqlite://')  # in-memory
    connection = db.engine.connect()
    transaction = connection.begin()
    Base.metadata.create_all(connection)

    session_factory = sessionmaker(bind=connection)
    session = scoped_session(session_factory)

    yield session

    transaction.rollback()
    connection.close()
    session.remove()


@pytest.fixture(scope="function")

3 Source : conftest.py
with MIT License
from art1415926535

def info():
    db = create_engine('sqlite://')  # in-memory
    connection = db.engine.connect()
    transaction = connection.begin()
    Base.metadata.create_all(connection)

    session_factory = sessionmaker(bind=connection)
    session = scoped_session(session_factory)

    yield ResolveInfo(*[None] * 9, context={'session': session})

    transaction.rollback()
    connection.close()
    session.remove()


@pytest.fixture(scope="function")

3 Source : conftest.py
with MIT License
from art1415926535

def info_and_user_query():
    db = create_engine('sqlite://')  # in-memory
    connection = db.engine.connect()
    transaction = connection.begin()
    Base.metadata.create_all(connection)

    session_factory = sessionmaker(bind=connection)
    session = scoped_session(session_factory)

    info = ResolveInfo(*[None] * 9, context={'session': session})
    user_query = session.query(models.User)

    yield info, user_query

    transaction.rollback()
    connection.close()
    session.remove()

3 Source : __init__.py
with GNU General Public License v3.0
from aryazakaria01

def start() -> scoped_session:
    engine = create_engine(DB_URL, client_encoding="utf8")
    LOGGER.info("PostgreSQL Connecting to database......")
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=True))


BASE = declarative_base()

3 Source : __init__.py
with GNU Affero General Public License v3.0
from aryazakaria01

def start() -> scoped_session:
    engine = create_engine(DB_URI, client_encoding="utf8")
    log.info("[PostgreSQL] Connecting to database......")
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=False))


BASE = declarative_base()

3 Source : hammer.py
with Apache License 2.0
from asharov

def iter_all_project_names(database_url=_default_database_url):
    engine = create_engine(database_url)
    _fail_unless_database_exists(engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    for project in session.query(Project):
        yield project.project_name
    session.close()


def iter_sources_and_tests(repository_path, configuration_file_path=None):

3 Source : hammer.py
with Apache License 2.0
from asharov

    def __init__(self, project_name, database_url=_default_database_url):
        start_time = datetime.datetime.now()
        self.project_name = project_name
        self._engine = create_engine(database_url)
        self._Session = sessionmaker(bind=self._engine)
        self._init_properties()
        if database_exists(self._engine.url):
            session = self._Session()
            self._build_repository_map(session)
            self._build_author_map(session)
            self._build_commit_map(session)
            session.close()
        print('Init time {}'.format(datetime.datetime.now() - start_time))

    def add_repository(self, repository_path, configuration_file_path=None, **kwargs):

3 Source : __init__.py
with GNU General Public License v3.0
from Awesome-RJ

def start() -> scoped_session:
    engine = create_engine(DB_URL, client_encoding="utf8")
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=False))


BASE = declarative_base()

3 Source : Database.py
with Apache License 2.0
from aynakeya

def checkDatabase(conn=srConfig.sqlalchemy_address):
    try:
        engine = create_engine(conn)
        DBSession = sessionmaker(bind=engine)
        dbs = DBSession()
        dbs.query(Songs).first()
        dbs.query(Fingerprints).first()
        return (True,0,"")
    except ProgrammingError as err:
        return (False,err.code,err.orig)
    except DatabaseError as err:
        return (False, err.code, err.orig)

def initSession(conn=srConfig.sqlalchemy_address):

3 Source : Database.py
with Apache License 2.0
from aynakeya

def initSession(conn=srConfig.sqlalchemy_address):
    # init connection
    engine = create_engine(conn, pool_size=srConfig.mysql_max_connection)
    # create sessionmaker:
    #DBSession = sessionmaker(bind=engine)
    DBSession = sessionmaker(bind=engine,autoflush=False, expire_on_commit=False)

    return DBSession, engine


def createTables(conn=srConfig.sqlalchemy_address):

3 Source : __init__.py
with GNU General Public License v3.0
from AyraHikari

def mulaisql() -> scoped_session:
	global DB_AVAIABLE
	engine = create_engine(DATABASE_URL, client_encoding="utf8")
	BASE.metadata.bind = engine
	try:
		BASE.metadata.create_all(engine)
	except exc.OperationalError:
		DB_AVAIABLE = False
		return False
	DB_AVAIABLE = True
	return scoped_session(sessionmaker(bind=engine, autoflush=False))

async def get_self():

3 Source : db.py
with MIT License
from Baiyuetribe

    def auto_commit_db(self):
        # 高并发下的数据库问题
        self.session = scoped_session(sessionmaker(bind=self.engine))
        try:
            yield
            self.session.commit()
        except Exception as e:
            # 加入数据库commit提交失败,必须回滚!!!
            self.session.rollback()
            print(e)
            raise e
        # finally:
        #     self.session.close()        


#路径设置
SQL_PATH = os.path.join(os.path.dirname(__file__),'../../public/sql')

3 Source : database.py
with MIT License
from BazaroZero

    def __init__(self, path: str, *args: Any, **kwargs: Any) -> None:
        self._engine = create_engine(path, *args, **kwargs)
        self._metadata = MetaData()
        self._metadata.reflect(self._engine)
        self._session = sessionmaker(self._engine)

    @property

3 Source : BBDD.py
with Apache License 2.0
from BBVA

def get_ts(name):

    DB_NAME = 'sqlite:///Timecop_modelsv1.db'
    engine = create_engine(DB_NAME)
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    query = session.query(TS)
    salida = session.query(TS).filter(TS.TS_name == name).order_by(desc('TS_update')).first()
    return ( salida.TS_data)


def set_ts(name, data):

3 Source : BBDD.py
with Apache License 2.0
from BBVA

def set_ts(name, data):

    DB_NAME = 'sqlite:///Timecop_modelsv1.db'
    engine = create_engine(DB_NAME)

    DBSession = sessionmaker(bind=engine)
    session = DBSession()


    new_TS = TS(TS_name=name, TS_data= data)
    session.add(new_TS)
    session.commit()


def new_model(name, winner, model,params,metric):

3 Source : BBDD.py
with Apache License 2.0
from BBVA

def new_model(name, winner, model,params,metric):

    DB_NAME = 'sqlite:///Timecop_modelsv1.db'
    engine = create_engine(DB_NAME)

    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    print ("Model saved")
    #print(model)

    new_model = Model(TS_name=name, TS_winner_name = winner, TS_model=bytearray(model),TS_model_params= params,TS_metric=metric)
    session.add(new_model)
    session.commit()

def get_best_model(name):

3 Source : BBDD.py
with Apache License 2.0
from BBVA

def get_all_models(name):
    DB_NAME = 'sqlite:///Timecop_modelsv1.db'
    engine = create_engine(DB_NAME)

    DBSession = sessionmaker(bind=engine)
    session = DBSession()

    query = session.query(Model).filter(Model.TS_name.like(name)).all()
    df = pd.DataFrame(query_to_dict(query))
    df.drop('TS_model',axis=1,inplace=True)
    return (df[['TS_name', 'TS_winner_name','TS_update']])



def get_winners(name):

3 Source : BBDD.py
with Apache License 2.0
from BBVA

def get_winners(name):
    DB_NAME = 'sqlite:///Timecop_modelsv1.db'
    engine = create_engine(DB_NAME)

    DBSession = sessionmaker(bind=engine)
    session = DBSession()

    query = session.query(Model)
    # for mt in query.all():
    #     print (unpack('H',(mt.TS_model)))
    #     print (mt.TS_name)
    #     print (mt.TS_winner_name)
    #     print (mt.TS_update)
    #filter(Note.message.like("%somestr%")
    winner_model_type = session.query(Model).filter(Model.TS_name.like(name)).filter(Model.TS_name.like('winner%')).order_by(desc('TS_update')).all()

    df = pd.DataFrame(query_to_dict(winner_model_type))
    df.drop('TS_model',axis=1,inplace=True)
    return (df[['TS_name', 'TS_winner_name','TS_update']])

3 Source : database.py
with GNU General Public License v3.0
from bdhowald

def _create_mysql_scoped_session(engine: Engine) -> ScopedSession:
    """Returns a scoped_session to the MySQL db connected to the given
    engine.
    :param engine: an engine connected to the target db.
    :return: a scoped_session to the db connected to the engine.
    """
    return scoped_session(
        sessionmaker(
            autocommit=False,
            autoflush=False,
            bind=engine,
            expire_on_commit=False))


def init_database() -> DatabaseConnection:

3 Source : conftest.py
with MIT License
from bergran

def get_session_and_client_fixture(request):
    from main import app
    # Set TEST_RUN environment to tell app that we are running under test environment to connect dummy test
    os.environ.setdefault('TEST_RUN', '1')

    from core.db.base import Base

    engine = create_engine(app.config.SQLALCHEMY_DATABASE_URI)
    session = sessionmaker(autocommit=False, autoflush=True, bind=engine)()

    request.cls.session = session
    request.cls.client = TestClient(app)
    request.cls.Base = Base


def _delete_database(dsn):

3 Source : conftest.py
with MIT License
from bergran

def _create_database_connection(app):
    from core.db.base import Base

    engine = create_engine(app.config.SQLALCHEMY_DATABASE_URI)
    session = sessionmaker(autocommit=False, autoflush=True, bind=engine)()

    import subprocess
    subprocess.call("cd {} && sh scripts/migrate.sh head".format(app.config.BASE_DIR), shell=True)
    return session, Base

3 Source : database_services.py
with GNU Affero General Public License v3.0
from betagouv

def with_session(function):
    def _with_session(*args, **kwargs):
        engine, connection, session = setup()
        connection = engine.connect()
        session = scoped_session(sessionmaker(bind=engine))
        result = function(session, *args, **kwargs)
        cleanup(session, connection)
        connection.close()
        return result

    return _with_session


def setup():

3 Source : database_services.py
with GNU Affero General Public License v3.0
from betagouv

def setup():
    engine = create_engine(database_url())
    connection = engine.connect()
    session = scoped_session(sessionmaker(bind=engine))
    return engine, connection, session


def cleanup(session, connection):

3 Source : conftest.py
with GNU Affero General Public License v3.0
from betagouv

def setup():
    def _setup():
        engine = create_engine(database_url("test"))
        connection = engine.connect()
        session = scoped_session(sessionmaker(bind=engine))
        return engine, connection, session

    return _setup


@fixture

3 Source : models.py
with MIT License
from blakebjorn

def init_db():
    if "sqlite:/" in config.DATABASE_URI:
        engine = create_engine(config.DATABASE_URI, connect_args={'timeout': 15}, echo=False)
    else:
        engine = create_engine(config.DATABASE_URI, echo=False)
    Base.metadata.create_all(engine)
    return sessionmaker(bind=engine, autoflush=False)()


session = init_db()

3 Source : sqlalchemy.py
with GNU Lesser General Public License v3.0
from Bogdanp

    def resolve(self, settings: Settings) -> EngineData:
        engine = create_engine(
            settings.strict_get("database_engine_dsn"),
            **settings.get("database_engine_params", {}),
        )

        session_factory = sessionmaker()
        session_factory.configure(bind=engine)
        return EngineData(engine, session_factory)


class SQLAlchemySessionComponent:

3 Source : relational.py
with MIT License
from bolinette

    def __init__(self, uri):
        super().__init__(relational=True)
        self._engine = create_engine(uri, echo=False)
        self._base = declarative_base()
        self._Session = sessionmaker(bind=self._engine)
        self._session = self._Session()
        self._tables = {}

    @property

3 Source : kernel.py
with MIT License
from buxx

    def init_client_db_session(self) -> None:
        kernel_logger.info('Initialize database connection to "client.db"')
        self._client_db_engine = create_engine(f"sqlite:///{self._client_db_path}")
        self._client_db_session = sessionmaker(bind=self._client_db_engine)()
        ClientSideDocument.metadata.create_all(self._client_db_engine)

    def init_server_db_session(self) -> None:

3 Source : kernel.py
with MIT License
from buxx

    def init_server_db_session(self) -> None:
        kernel_logger.info("Initialize database connection to server database")
        self._server_db_engine = create_engine(
            f"postgresql+psycopg2://{self.server_db_user}:{self.server_db_password}@"
            f"127.0.0.1:5432/{self.server_db_name}"
        )
        self._server_db_session = sessionmaker(bind=self._server_db_engine)()
        ServerSideDocument.metadata.create_all(self._server_db_engine)

    def init(self) -> None:

3 Source : sessions.py
with GNU General Public License v2.0
from c0rv4x

    def __init__(self):
        self.engine = create_engine(
            'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(
                CONFIG['postgres']['username'],
                CONFIG['postgres']['password'],
                CONFIG['postgres']['host'],
                CONFIG['postgres']['port'],
                CONFIG['postgres']['database']
            ),
            # echo=True,
            poolclass=NullPool,
            use_batch_mode=True)
        self.session_builder = sessionmaker(
            bind=self.engine, expire_on_commit=False)

    def get_new_session(self):

3 Source : database_functions.py
with MIT License
from casemsee

def db_session(config = scheduling_plan_local):
	"""
	Create database engine for the energy management system
	:return: Database Session
	"""
	db_str = 'mysql+pymysql://' + config["user_name"] + ':' + config['password'] + '@' + config['ip_address'] + '/' + config['db_name']
	engine = create_engine(db_str, echo=False)
	Session = sessionmaker(bind=engine)

	return Session

See More Examples