예제 #1
0
def get_dbsession(settings):
    engine = engine_from_config(settings)
    maker = sessionmaker()
    maker.configure(bind=engine)
    session = maker()
    register(session)
    return session
예제 #2
0
 def register(cls, name, scoped, engine):
     if scoped:
         cls.sessions[name] = scoped_session(sessionmaker(bind=engine))
         register(cls.sessions[name])
     else:
         cls.sessions[name] = sessionmaker(bind=engine)
     return cls.sessions[name]
예제 #3
0
def connect(db_url=None):
    if db_url is None:
        db_url = config.get('mysqld', 'url')

    log.info("Connecting to database")
    log.debug("DB URL: %s", db_url)

    db_url = create_mysql_db(db_url)

    global engine

    db_pool_size = config.get('mysqld', 'pool_size', 5)
    db_max_overflow = config.get('mysqld', 'max_overflow', 10)
    if db_url.startswith('sqlite'):
        engine = create_engine(db_url, encoding='utf8')
    else:
        engine = create_engine(db_url,
                               encoding='utf8',
                               pool_size=db_pool_size,
                               max_overflow=db_max_overflow)

    global DBSession

    maker = sessionmaker(bind=engine, autoflush=False, autocommit=False)
    DBSession = scoped_session(maker)
    register(DBSession)


    global DeclarativeBase
    try:
        DeclarativeBase.metadata.create_all(engine, checkfirst=True)
    except sqlalchemy.exc.OperationalError as err:
        log.warning("Error creating database: %s", err)
예제 #4
0
 def _default_dbsession(self):
     registry = get_current_registry()
     engine = sqlalchemy.engine_from_config(registry.settings)
     session = scoped_session(sessionmaker())
     session.configure(bind=engine)
     register(session)
     return session
예제 #5
0
def db_session(request):
    """Session for SQLAlchemy."""
    from pyramid_fullauth.models import Base  # pylint:disable=import-outside-toplevel

    if request.param == "sqlite":
        connection = "sqlite:///fullauth.sqlite"
    elif request.param == "mysql":
        request.getfixturevalue("mysql")  # takes care of creating database
        connection = "mysql+mysqldb://root:@127.0.0.1:3307/tests?charset=utf8"
    elif request.param == "postgresql":
        request.getfixturevalue(
            "postgresql")  # takes care of creating database
        connection = "postgresql+psycopg2://postgres:@127.0.0.1:5433/tests"

    engine = create_engine(connection, echo=False, poolclass=NullPool)
    pyramid_basemodel.Session = scoped_session(sessionmaker())
    register(pyramid_basemodel.Session)
    pyramid_basemodel.bind_engine(engine,
                                  pyramid_basemodel.Session,
                                  should_create=True,
                                  should_drop=True)

    def destroy():
        transaction.commit()
        Base.metadata.drop_all(engine)

    request.addfinalizer(destroy)

    return pyramid_basemodel.Session
예제 #6
0
def registerSessionEvents(session):
    current = transaction.get();
    if not current.description:
       raise BstSystemError('Current transaction has no description!')
   
    logger.debug('Joining transaction [%s, txn.%d]', str(current.description), get_thread_ident())
    register(session)
예제 #7
0
def main():
    args = _parse_args()
    reporter = Reporter(args)
    try:
        engine = sqlalchemy.create_engine(args.db)
        factory = sqlalchemy.orm.sessionmaker(bind=engine)
        register(factory)
        session = sqlalchemy.orm.scoped_session(factory)
    except Exception as e:
        reporter.error(['connection'], e)
        raise

    tables = session.execute("""
    SELECT table_schema, table_name FROM information_schema.tables
    WHERE table_type='BASE TABLE' AND table_schema IN :schemas
    """,
                             params={'schemas': tuple(args.schema)})
    for schema, table in tables:
        try:
            do_table(session, schema, table, reporter)
        except Exception as e:
            reporter.error([schema, table], e)

    if args.extra:
        for pos, extra in enumerate(args.extra):
            try:
                do_extra(session, extra, reporter)
            except Exception as e:
                reporter.error(['extra', str(pos + 1)], e)

    reporter.commit()
    transaction.abort()
    reporter.report_error()
예제 #8
0
 def sessionFactory(self):
     engine_factory = component.getUtility(IEngineFactory, name=self.engine)
     kw = self.kw.copy()
     kw['bind'] = engine_factory()
     session = sqlalchemy.orm.create_session(**kw)
     register(session)
     return session
예제 #9
0
def get_tm_session(
        session_factory: Callable,
        transaction_manager: ThreadTransactionManager,
) -> Session:
    """Return a db session being managed by the transaction manager."""
    db_session = session_factory()
    register(db_session, transaction_manager=transaction_manager)
    return db_session
예제 #10
0
def registerSessionEvents(session):
    current = transaction.get()
    if not current.description:
        raise BstSystemError('Current transaction has no description!')

    logger.debug('Joining transaction [%s, txn.%d]', str(current.description),
                 get_thread_ident())
    register(session)
예제 #11
0
def create_session(
    config: Optional[pyramid.config.Configurator],
    name: str,
    url: str,
    slave_url: Optional[str] = None,
    force_master: Optional[Iterable[str]] = None,
    force_slave: Optional[Iterable[str]] = None,
    **engine_config: Any,
) -> Union[sqlalchemy.orm.Session, sqlalchemy.orm.scoped_session]:
    """
    Create a SQLAlchemy session.

    With an accompanying tween that switches between the master and the slave DB
    connection.

    The slave DB will be used for anything that is GET and OPTIONS queries. The master DB will be used for
    all the other queries. You can tweak this behavior with the force_master and force_slave parameters.
    Those parameters are lists of regex that are going to be matched against "{VERB} {PATH}". Warning, the
    path includes the route_prefix.

    Arguments:

        config: The pyramid Configuration object. If None, only master is used
        name: The name of the check
        url: The URL for the master DB
        slave_url: The URL for the slave DB
        force_master: The method/paths that needs to use the master
        force_slave: The method/paths that needs to use the slave
        engine_config: The rest of the parameters are passed as is to the sqlalchemy.create_engine function

    Returns: The SQLAlchemy session
    """
    warnings.warn(
        "create_session function is deprecated; use init and request.dbsession instead"
    )
    if slave_url is None:
        slave_url = url

    rw_engine = sqlalchemy.create_engine(url, **engine_config)
    factory = sqlalchemy.orm.sessionmaker(bind=rw_engine)
    register(factory)
    db_session = sqlalchemy.orm.scoped_session(factory)

    # Setup a slave DB connection and add a tween to use it.
    if url != slave_url and config is not None:
        LOG.info("Using a slave DB for reading %s", name)
        ro_engine = sqlalchemy.create_engine(slave_url, **engine_config)
        _add_tween(config, name, db_session, force_master, force_slave)
        rw_engine.c2c_name = name + "_master"
        ro_engine.c2c_name = name + "_slave"
    else:
        rw_engine.c2c_name = name
        ro_engine = rw_engine

    db_session.c2c_rw_bind = rw_engine
    db_session.c2c_ro_bind = ro_engine
    return db_session
예제 #12
0
def setup_session(
    config: pyramid.config.Configurator,
    master_prefix: str,
    slave_prefix: Optional[str] = None,
    force_master: Optional[Iterable[str]] = None,
    force_slave: Optional[Iterable[str]] = None,
) -> Tuple[Union[sqlalchemy.orm.Session, sqlalchemy.orm.scoped_session],
           sqlalchemy.engine.Engine, sqlalchemy.engine.Engine, ]:
    """
    Create a SQLAlchemy session.

    With an accompanying tween that switches between the master and the slave DB
    connection. Uses prefixed entries in the application's settings.

    The slave DB will be used for anything that is GET and OPTIONS queries. The master DB will be used for
    all the other queries. You can tweak this behavior with the force_master and force_slave parameters.
    Those parameters are lists of regex that are going to be matched against "{VERB} {PATH}". Warning, the
    path includes the route_prefix.

    Arguments:

        config: The pyramid Configuration object
        master_prefix: The prefix for the master connection configuration entries in the application \
                          settings
        slave_prefix: The prefix for the slave connection configuration entries in the application \
                         settings
        force_master: The method/paths that needs to use the master
        force_slave: The method/paths that needs to use the slave

    Returns: The SQLAlchemy session, the R/W engine and the R/O engine
    """
    warnings.warn(
        "setup_session function is deprecated; use init and request.dbsession instead"
    )
    if slave_prefix is None:
        slave_prefix = master_prefix
    settings = config.registry.settings
    rw_engine = sqlalchemy.engine_from_config(settings, master_prefix + ".")
    rw_engine.c2c_name = master_prefix
    factory = sqlalchemy.orm.sessionmaker(bind=rw_engine)
    register(factory)
    db_session = sqlalchemy.orm.scoped_session(factory)

    # Setup a slave DB connection and add a tween to use it.
    if settings[master_prefix + ".url"] != settings.get(slave_prefix + ".url"):
        LOG.info("Using a slave DB for reading %s", master_prefix)
        ro_engine = sqlalchemy.engine_from_config(config.get_settings(),
                                                  slave_prefix + ".")
        ro_engine.c2c_name = slave_prefix
        tween_name = master_prefix.replace(".", "_")
        _add_tween(config, tween_name, db_session, force_master, force_slave)
    else:
        ro_engine = rw_engine

    db_session.c2c_rw_bind = rw_engine
    db_session.c2c_ro_bind = ro_engine
    return db_session, rw_engine, ro_engine
예제 #13
0
 def __call__(self, environ, start_response):
     session = session_factory()
     register(session)
     environ[self.session_key] = session
     try:
         result = self.next_app(environ, start_response)
         return result
     finally:
         session.close()
예제 #14
0
def create_session(request):
    sessionmaker = request.registry['db_sessionmaker']
    session = sessionmaker()
    register(session, transaction_manager=request.tm)

    def cleanup(request):
        session.close()

    request.add_finished_callback(cleanup)
    return session
예제 #15
0
def init_sqlalchemy(settings, session=None, **kwargs):
    if not session:
        session = scoped_session(sessionmaker())
        register(session)

    engine = sqlalchemy_engine_from_config(settings, **kwargs)
    session.configure(bind=engine)
    Base.metadata.bind = engine

    return session
예제 #16
0
def _make_session(dsn):
    engine = create_engine(dsn,  # , encoding="utf8"
                           pool_recycle=1800,
                           pool_pre_ping=True,
                           connect_args={'timeout': 60}
                           )
    Session = scoped_session(sessionmaker(bind=engine))
    register(Session, keep_session=True)

    return Session()
예제 #17
0
def add_languages_to_db():
    """Add supported pygments languages to the database"""
    db = get_session(REAL_DATABASE_URL)
    register(db, transaction_manager=transaction.manager)
    with transaction.manager:
        for lang in LANGUAGES:
            language = Language(name=lang)
            db.add(language)
    db.close()
    click.secho('successfully inserted languages to the database!', fg='green')
예제 #18
0
def add_styles_to_db():
    """Add supported pygments styles to the database"""
    db = get_session(REAL_DATABASE_URL)
    register(db, transaction_manager=transaction.manager)
    with transaction.manager:
        for item in STYLES:
            style = Style(name=item)
            db.add(style)
    db.close()
    click.secho('successfully inserted styles to the database!', fg='green')
예제 #19
0
파일: __init__.py 프로젝트: dgabriele/sfdd
def add_db_session_request_method(config, engine, use_tm=True):
    config.registry.DB_Session = sessionmaker(bind=engine)
    if use_tm:
        # add sqlalchemy session to active transaction
        register(config.registry.DB_Session)

    def db_session(request):
        return config.registry.DB_Session()

    config.add_request_method(db_session, reify=True)
예제 #20
0
def add_db_session_request_method(config, engine, use_tm=True):
    config.registry.DB_Session = sessionmaker(bind=engine)
    if use_tm:
        # add sqlalchemy session to active transaction
        register(config.registry.DB_Session)

    def db(request):
        return config.registry.DB_Session()

    config.add_request_method(db, reify=True)
예제 #21
0
    def __init__(self, db_path):
        self.base = declarative_base()
        self.engine = create_engine(db_path, convert_unicode=True, pool_size=0)

        #self.base.prepare(self.engine, reflect=True)
        self.session = scoped_session(
            sessionmaker(
                bind=self.engine,
                extension=ZopeTransactionExtension(keep_session=True)))

        register(self.session, keep_session=True)
예제 #22
0
 def __call__(self, context, request):
     """
     :type context: Any
     :type request: pyramid.request.Request
     :rtype: sqlalchemy.orm.session.Session
     """
     session = self.factory()
     event = DBSessionCreated(session=session, name=self.name)
     request.registry.notify(event)
     register(session, transaction_manager=request.tm)
     return session
예제 #23
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)

    sqlalchemy_url_value = environ.get(
        'MARIADB_STRING_CONNECTION',
        'mysql://*****:*****@172.17.0.3:3306/matomo')
    settings.update({'sqlalchemy.url': sqlalchemy_url_value})

    application_url_value = environ.get('APPLICATION_URL',
                                        'http://127.0.0.1:6543')
    settings.update({'application.url': application_url_value})

    DBSession = scoped_session(sessionmaker())
    register(DBSession)

    engine = engine_from_config(settings, 'sqlalchemy.')
    Base.metadata.create_all(engine)
    DBSession.configure(bind=engine)

    file_counter_report = os.path.join(os.getcwd(),
                                       '/app/static/counter_report.json')
    with transaction.manager:
        with open(file_counter_report) as f:
            application_url = settings.get('application.url')
            array = json.load(f)

            for dic in array:
                for v in dic.values():

                    report = Report(report_id=v['Report_ID'],
                                    name=v['Report_Name'],
                                    release=v['Release'],
                                    description=v['Report_Description'],
                                    path=application_url + v['Path'])

                    DBSession.add(report)

        status = Status()
        status.description = "COUNTER Usage Reports for SciELO platform."
        status.note = ""
        status.registry_url = application_url + '/registration'
        status.service_active = True
        DBSession.add(status)

        alert = Alert()
        alert.description = "Reports DR, DR_D1, DR_D2, PR, PR_1, TR_J2 and TR_J3 are currently unavailable."
        alert.created = datetime.now().isoformat()
        alert.is_active = True
        DBSession.add(alert)
예제 #24
0
 async def dispatch(self, request: Request,
                    call_next: Callable) -> Response:
     engine = create_engine(self.database_url,
                            connect_args={'check_same_thread': False})
     session_class = sessionmaker(bind=engine)
     db = session_class()
     register(db, transaction_manager=transaction.manager)
     request.state.db = db
     with transaction.manager:
         response = await call_next(request)
     db.close()
     return response
예제 #25
0
def main(argv=sys.argv):
    alembic_configfile = os.path.realpath(
        os.path.join(os.path.dirname(os.path.abspath(__file__)),
                     '../../../alembic.ini'))
    alembic_config = Config(alembic_configfile)

    settings_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 'migration.ini')
    settings = get_appsettings(settings_file)

    engine_target = engine_from_config(settings, 'sqlalchemy_target.')
    engine_source = engine_from_config(settings, 'sqlalchemy_source.')

    logging.basicConfig()
    logging.getLogger('sqlalchemy.engine').setLevel(logging.WARN)

    Session = sessionmaker()  # noqa
    register(Session)
    session = Session(bind=engine_target)

    # set up the target database
    setup_db(alembic_config, session)

    connection_source = engine_source.connect()

    batch_size = 1000
    MigrateAreas(connection_source, session, batch_size).migrate()
    MigrateUserProfiles(connection_source, session, batch_size).migrate()
    MigrateUsers(connection_source, session, batch_size).migrate()
    MigrateSummits(connection_source, session, batch_size).migrate()
    MigrateParkings(connection_source, session, batch_size).migrate()
    MigrateSites(connection_source, session, batch_size).migrate()
    MigrateProducts(connection_source, session, batch_size).migrate()
    MigrateHuts(connection_source, session, batch_size).migrate()
    MigrateRoutes(connection_source, session, batch_size).migrate()
    MigrateMaps(connection_source, session, batch_size).migrate()
    MigrateOutings(connection_source, session, batch_size).migrate()
    MigrateImages(connection_source, session, batch_size).migrate()
    MigrateXreports(connection_source, session, batch_size).migrate()
    MigrateArticles(connection_source, session, batch_size).migrate()
    MigrateBooks(connection_source, session, batch_size).migrate()
    MigrateVersions(connection_source, session, batch_size).migrate()
    MigrateAssociations(connection_source, session, batch_size).migrate()
    CreateClimbingSiteRoutes(connection_source, session, batch_size).migrate()
    SetRouteTitlePrefix(connection_source, session, batch_size).migrate()
    SetDefaultGeometries(connection_source, session, batch_size).migrate()
    MigrateAreaAssociations(connection_source, session, batch_size).migrate()
    MigrateMapAssociations(connection_source, session, batch_size).migrate()
    MigrateMailinglists(connection_source, session, batch_size).migrate()
    UpdateSequences(connection_source, session, batch_size).migrate()
    InitFeed(connection_source, session, batch_size).migrate()
    AnalyzeAllTables(connection_source, session, batch_size).migrate()
예제 #26
0
def initialize(backend_settings,
               session_override=None):
    # Allows for the front end to define its own session scope
    global DBSession
    if session_override is None:
        DBSession = scoped_session(sessionmaker())
        register(DBSession, keep_session=True)
    else:
        DBSession = session_override

    engine = engine_from_config(backend_settings, 'sqlalchemy.')
    Base.metadata.bind = engine
    DBSession.configure(bind=engine)
예제 #27
0
def shell():
    """Creates a python interpreter to interact with pastebin modules"""
    db = get_session(REAL_DATABASE_URL)
    register(db, transaction_manager=transaction.manager)
    with transaction.manager:
        code.interact(banner='Interactive pastebin console',
                      exitmsg='Good bye!',
                      local={
                          'pastebin': pastebin,
                          'db': db,
                          'transaction': transaction
                      })
    db.close()
예제 #28
0
def create_from_config(config, prefix="", with_transaction=True):
    """Create a PostgreSQLClient client using settings in the provided config.
    """
    if sqlalchemy is None:
        message = ("PostgreSQL SQLAlchemy dependency missing. "
                   "Refer to installation section in documentation.")
        raise ImportWarning(message)

    from zope.sqlalchemy import register, invalidate
    from sqlalchemy.orm import sessionmaker, scoped_session

    settings = {**config.get_settings()}

    # Custom Kinto settings, unsupported by SQLAlchemy.
    blacklist = [prefix + setting for setting in BLACKLISTED_SETTINGS]
    filtered_settings = {
        k: v
        for k, v in settings.items() if k not in blacklist
    }
    transaction_per_request = with_transaction and filtered_settings.pop(
        "transaction_per_request", False)
    url = filtered_settings[prefix + "url"]
    existing_client = _CLIENTS[transaction_per_request].get(url)
    if existing_client:
        msg = "Reuse existing PostgreSQL connection. " f"Parameters {prefix}* will be ignored."
        warnings.warn(msg)
        return existing_client

    # Initialize SQLAlchemy engine from filtered_settings.
    poolclass_key = prefix + "poolclass"
    filtered_settings.setdefault(poolclass_key,
                                 ("kinto.core.storage.postgresql."
                                  "pool.QueuePoolWithMaxBacklog"))
    filtered_settings[poolclass_key] = config.maybe_dotted(
        filtered_settings[poolclass_key])
    engine = sqlalchemy.engine_from_config(filtered_settings,
                                           prefix=prefix,
                                           url=url)

    # Initialize thread-safe session factory.
    session_factory = scoped_session(sessionmaker(bind=engine))
    if transaction_per_request:
        # Plug with Pyramid transaction manager
        register(session_factory)

    # Store one client per URI.
    commit_manually = not transaction_per_request
    client = PostgreSQLClient(session_factory, commit_manually, invalidate)
    _CLIENTS[transaction_per_request][url] = client
    return client
예제 #29
0
    def __init__(self):
        self.DeclarativeBase = declarative_base()
        self.DBSession = scoped_session(
            sessionmaker(autoflush=True, autocommit=False))
        register(self.DBSession)

        class User(self.DeclarativeBase):
            __tablename__ = 'tg_user'

            user_id = Column(Integer, autoincrement=True, primary_key=True)
            user_name = Column(Unicode(16), unique=True, nullable=False)
            email_address = Column(Unicode(255), unique=True, nullable=False)
            display_name = Column(Unicode(255))
            password = Column(Unicode(255), nullable=False)

        self.User = User
예제 #30
0
def db_session(request):
    """Session for SQLAlchemy."""
    from pyramid_localize.models import Base  # pylint:disable=import-outside-toplevel

    engine = create_engine("sqlite:///localize.sqlite", echo=False, poolclass=NullPool)
    pyramid_basemodel.Session = scoped_session(sessionmaker())
    register(pyramid_basemodel.Session)
    pyramid_basemodel.bind_engine(engine, pyramid_basemodel.Session, should_create=True, should_drop=True)

    def destroy():
        transaction.commit()
        Base.metadata.drop_all(engine)

    request.addfinalizer(destroy)

    return pyramid_basemodel.Session
예제 #31
0
def connect(db_url=None):
    if db_url is None:
        db_url = config.get('mysqld', 'url')

    log.info("Connecting to database")
    if db_url.find('@') >= 0:
        log.info("DB URL: %s", db_url.split('@')[1])
    else:
        log.info("DB URL: %s", db_url)

    db_url = create_mysql_db(db_url)

    global engine

    if db_url.startswith('sqlite'):
        engine = create_engine(db_url, encoding='utf8')
    else:

        db_pool_size = int(config.get('mysqld', 'pool_size', 5))
        db_pool_recycle = int(config.get('mysqld', 'pool_recycle', 300))
        db_max_overflow = int(config.get('mysqld', 'max_overflow', 10))
        ssl_ca = config.get('mysqld', 'ssl_ca', False)
        connect_args = {}
        if ssl_ca:
            connect_args['ssl'] = {'ssl_ca': ssl_ca}

        engine = create_engine(db_url,
                               encoding='utf8',
                               connect_args=connect_args,
                               pool_recycle=db_pool_recycle,
                               pool_size=db_pool_size,
                               max_overflow=db_max_overflow)

    global DBSession

    maker = sessionmaker(bind=engine, autoflush=False, autocommit=False)
    DBSession = scoped_session(maker)
    register(DBSession)

    global DeclarativeBase
    try:
        DeclarativeBase.metadata.create_all(engine, checkfirst=True)
    except sqlalchemy.exc.OperationalError as err:
        log.warning("Error creating database: %s", err)

    return db_url
예제 #32
0
def create_test_database():
    """
    Create a clean database on every test case.
    For safety, we should abort if a database already exists.
    """
    assert not database_exists(
        TEST_DATABASE_URL), 'Test database already exists. Aborting tests.'
    create_database(TEST_DATABASE_URL)
    engine = create_engine(TEST_DATABASE_URL,
                           connect_args={'check_same_thread': False})
    session_class = sessionmaker(bind=engine)
    db = session_class()
    register(db, transaction_manager=transaction.manager)
    Base.metadata.create_all(engine)
    create_test_objects(db)
    yield
    db.close()
    drop_database(TEST_DATABASE_URL)
예제 #33
0
    def __init__(self, url):
        """
        Simple wrapper class to have all connection specific stuff in one simple accessible place.

        :param url: The connection string which is used to let the api connect with the desired database.
        It must have the form as described here:
        http://docs.sqlalchemy.org/en/latest/core/engines.html
        :type url: str
        """
        self.url = url
        if 'cx_oracle' in self.url:
            self.engine = create_engine(self.url,
                                        pool_size=1,
                                        coerce_to_unicode=True)
        else:
            self.engine = create_engine(self.url, pool_size=1)
        self.session = scoped_session(sessionmaker(bind=self.engine))
        register(self.session)
예제 #34
0
파일: fill_index.py 프로젝트: c2corg/v6_api
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    logging.getLogger('sqlalchemy.engine').setLevel(logging.ERROR)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    Session = sessionmaker()  # noqa
    register(Session)
    session = Session(bind=engine)
    configure_es_from_config(settings)

    batch_size = int(settings.get('elasticsearch.batch_size.fill_index', 1000))

    with transaction.manager:
        fill_index(session, batch_size)
예제 #35
0
def initialize(ini_filenames=(os.path.expanduser('~/.pydiditrc'),
                              os.path.expanduser('~/.pydidit-backendrc')),
               external_config_fp=None,
               session_override=None):
    # Allows for the front end to define its own session scope
    global DBSession
    if session_override is None:
        DBSession = scoped_session(sessionmaker())
        register(DBSession, keep_session=True)
    else:
        DBSession = session_override

    ini = ConfigParser.SafeConfigParser()
    ini.read(ini_filenames)
    allow_external_config = ini.getboolean('backend', 'allow_external_config')
    if allow_external_config is True and external_config_fp is not None:
        ini.readfp(external_config_fp)
    settings = dict(ini.items('backend'))

    engine = engine_from_config(settings, 'sqlalchemy.')
    Base.metadata.bind = engine
    DBSession.configure(bind=engine)
예제 #36
0
def includeme(config):
    # We'll configure the DB connection from this.
    settings = config.get_settings()

    # by including pyramid_tm here, it doesn't need to be in the ini file.
    config.include('pyramid_tm')

    # connect to the DB and make a sessionmaker
    engine = engine_from_config(settings, 'sqlalchemy.')
    maker = sessionmaker()
    # register the sessionmaker with the zope transaction manager
    # all sessions created from this will be hooked up
    register(maker)
    # and finally connect the session to the engine
    maker.configure(bind=engine)

    # Store the sessionmaker in the registry; this will come in handy for utils
    config.registry['db_sessionmaker'] = maker

    # Every request will have a db_session property. The first time
    # you use it, it creates a session, and then replaces the property
    # with that session.
    config.add_request_method(lambda request: maker(), 'db_session', reify=True)
예제 #37
0
from colander import null
from pyramid.security import Allow
from pyramid.security import Authenticated
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from zope.sqlalchemy import register


metadata = MetaData()
db_session = scoped_session(sessionmaker())
register(db_session)


class Base(object):

    __acl__ = [
        (Allow, Authenticated, ['view']),
        (Allow, 'owner', ['edit', 'delete']),
    ]

    plural = True

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    @property
    def columns(self):
예제 #38
0
"""SQLAlchemy Metadata and Session object"""
from sqlalchemy import orm
from sqlalchemy import schema
from sqlalchemy.ext.declarative import declarative_base
from zope.sqlalchemy import register

#: SQLAlchemy session manager.  Updated by
# :py:func:`pyramid_sqlalchemy.init_sqlalchemy`.
Session = orm.scoped_session(orm.sessionmaker())
register(Session)

#: Global metadata. If you have multiple databases with overlapping table
#: names, you'll need a metadata for each database
metadata = schema.MetaData()

#: Base classes for models using declarative syntax
BaseObject = declarative_base(metadata=metadata)

__all__ = ['Session', 'metadata', 'BaseObject']
예제 #39
0
#
# ratbot comics is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# ratbot comics 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
# ratbot comics. If not, see <http://www.gnu.org/licenses/>.

from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    relationship,
    synonym,
    )
from zope.sqlalchemy import register


__all__ = ['DBSession']


# Global database session factory
DBSession = scoped_session(sessionmaker())
register(DBSession)

예제 #40
0
 def _make_session(self):
     engine = create_engine(os.environ.get("DB"))
     Session = scoped_session(sessionmaker(bind=engine))
     register(Session, keep_session=True)
     session = Session()
     return session
예제 #41
0
def create_session(request):
    sessionmaker = request.registry['db_sessionmaker']
    session = sessionmaker()
    register(session, transaction_manager=request.tm)
    return session
예제 #42
0
def register_session(url=None,
                    name=u'',
                    engine=None,
                    echo=None,
                    transactional=True,
                    scoped=True,
                    twophase=True):
    """
    Create a :class:`~sqlalchemy.orm.session.Session` class and
    register it for later use.

    Generally, you'll only need to pass in a :mod:`SQLAlchemy`
    connection URL. If you want to register multiple sessions for a
    particular application, then you should name them.
    If you want to provide specific engine configuration, then you can
    pass in an :class:`~sqlalchemy.engine.base.Engine` instance.
    In that case, you must not pass in a URL.

    :param echo: If `True`, then all SQL will be echoed to the python
      logging framework. This option cannot be specified if you pass in
      an engine.

    :param scoped: If `True`, then :func:`get_session` will return a distinct
      session for each thread that it is called from but, within that thread,
      it will always return the same session. If it is `False`, every call
      to :func:`get_session` will return a new session.
    
    :param transactional:

      If `True`, a :mod:`SQLAlchemy` extension will
      be used that that enables the :mod:`transaction` package to
      manage the lifecycle of the SQLAlchemy session (eg:
      :meth:`~sqlalchemy.orm.session.Session.begin`/:meth:`~sqlalchemy.orm.session.Session.commit`/:meth:`~sqlalchemy.orm.session.Session.rollback`).
      This can only be done when scoped sessions are used.

      If `False`, you will need to make sure you call
      :meth:`~sqlalchemy.orm.session.Session.begin`/:meth:`~sqlalchemy.orm.session.Session.commit`/:meth:`~sqlalchemy.orm.session.Session.rollback`,
      as appropriate, yourself. 

    :param twophase: By default two-phase transactions are used where
      supported by the underlying database. Where this causes problems,
      single-phase transactions can be used for all engines by passing this
      parameter as `False`.

    """
    if (engine and url) or not (engine or url):
        raise TypeError('Must specify engine or url, but not both')

    if transactional and not scoped:
        raise TypeError(
            'Transactions can only be managed when using scoped sessions'
            )
        
    if engine:
        if echo:
            raise TypeError('Cannot specify echo if an engine is passed')
    else:
        engine = create_engine(url, echo=echo)

    logger.info('Registering session for %r with name %r',
                engine.url, name)

    params = dict(
            bind = engine,
            autoflush=True,
            autocommit=False,
            )

    if transactional:
        if twophase and engine.dialect.name in ('postgresql', 'mysql'):
            params['twophase']=True

    Session = sessionmaker(**params)
    
    if scoped:
        Session = scoped_session(Session)

    if transactional:
        register(Session, initial_state=STATUS_CHANGED)
    
    getSiteManager().registerUtility(
        Session,
        provided=ISession,
        name=name,
        )