• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sqlahelper.add_engine函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sqlahelper.add_engine函数的典型用法代码示例。如果您正苦于以下问题:Python add_engine函数的具体用法?Python add_engine怎么用?Python add_engine使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了add_engine函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test1

 def test1(self):
     import transaction
     Base = sqlahelper.get_base()
     class Person(Base):
         __tablename__ = "people"
         id = sa.Column(sa.Integer, primary_key=True)
         first_name = sa.Column(sa.Unicode(100), nullable=False)
         last_name = sa.Column(sa.Unicode(100), nullable=False)
     engine = sa.create_engine(self.db1.url)
     sqlahelper.add_engine(engine)
     Base.metadata.create_all()
     fred = Person(id=1, first_name=u"Fred", last_name=u"Flintstone")
     wilma = Person(id=2, first_name=u"Wilma", last_name=u"Flintstone")
     barney = Person(id=3, first_name=u"Barney", last_name=u"Rubble")
     betty = Person(id=4, first_name=u"Betty", last_name=u"Rubble")
     Session = sqlahelper.get_session()
     sess = Session()
     sess.add_all([fred, wilma, barney, betty])
     transaction.commit()
     sess.expunge_all()
     del fred, wilma, barney, betty
     # Can we get back a record?
     barney2 = sess.query(Person).get(3)
     self.assertEqual(barney2.id, 3)
     self.assertEqual(barney2.first_name, u"Barney")
     self.assertEqual(barney2.last_name, u"Rubble")
     sa.select([Person.first_name])
     # Can we iterate the first names in reverse alphabetical order?
     q = sess.query(Person.first_name).order_by(Person.first_name.desc())
     result = [x.first_name for x in q]
     control = [u"Wilma", u"Fred", u"Betty", u"Barney"]
     self.assertEqual(result, control)
开发者ID:pyramid-collective,项目名称:SQLAHelper,代码行数:32,代码来源:tests.py


示例2: create_engine

def create_engine(create_engine_dotted, dburl):
    if create_engine_dotted:
        return import_symbol(create_engine_dotted)(dburl)
    else:
        engine = sa.create_engine(dburl)
        sqlahelper.add_engine(engine)
        return engine
开发者ID:podhmo,项目名称:spectacles,代码行数:7,代码来源:alchemy.py


示例3: setUpCommon

def setUpCommon():
    import c2cgeoportal
    c2cgeoportal.schema = 'main'
    c2cgeoportal.srid = 21781
    c2cgeoportal.caching.init_region({'backend': 'dogpile.cache.memory'})

    # if test.in does not exist (because the z3c.recipe.filetemplate
    # part hasn't been executed) then db_url is None
    if db_url is None:  # pragma: nocover
        return

    # verify that we have a working database connection before going
    # forward
    from sqlalchemy import create_engine
    from sqlalchemy.exc import OperationalError
    engine = create_engine(db_url)
    try:
        engine.connect()
    except OperationalError:  # pragma: nocover
        return

    import sqlahelper
    sqlahelper.add_engine(engine)

    from c2cgeoportal.models import Base
    Base.metadata.create_all()
开发者ID:bbinet,项目名称:c2cgeoportal,代码行数:26,代码来源:__init__.py


示例4: initialized

def initialized(ev):
    PTAH = ptah.get_settings(ptah.CFG_ID_PTAH, ev.registry)

    # mail
    PTAH['Mailer'] = DummyMailer()
    PTAH['full_email_address'] = formataddr(
        (PTAH['email_from_name'], PTAH['email_from_address']))

    # sqla
    SQLA = ptah.get_settings(ptah.CFG_ID_SQLA, ev.registry)
    url = SQLA['url']
    if url:
        engine_args = {}
        if SQLA['cache']:
            cache = {}
            engine_args['execution_options'] = \
                {'compiled_cache': cache}
            SQLA['sqlalchemy_cache'] = cache
        try:
            engine = sqlahelper.get_engine()
        except: # pragma: no cover
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': url}, 'sqlalchemy.', **engine_args)
            sqlahelper.add_engine(engine)

    # ptah manage
    if PTAH['manage']:
        ev.config.add_route(
            'ptah-manage', '/ptah-manage/*traverse',
            factory=ptah.manage.PtahManageRoute, use_global_views=True)
        ptah.manage.set_access_manager(
            ptah.manage.PtahAccessManager())
开发者ID:runyaga,项目名称:ptah,代码行数:32,代码来源:ptahsettings.py


示例5: main

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    config = Configurator(settings=settings)
    settings = config.get_settings()
    settings.update(yaml.load(file(settings.get("app.cfg"))))

    add_mako_renderer(config, ".html")
    add_mako_renderer(config, ".js")

    engine = engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)
    dbreflection.init(engine)

    config.set_authorization_policy(ACLAuthorizationPolicy())

    config.add_request_method(
        _create_get_user_from_request(settings),
        name="user",
        property=True
    )

    authtkt_authentication_policy = AuthTktAuthenticationPolicy(
        settings.get('authtkt')['secret'],
        cookie_name=settings.get('authtkt')['cookie_name'],
        hashalg='sha512'
    )

    remote_user_authentication_policy = RemoteUserAuthenticationPolicy()
    policies = [remote_user_authentication_policy, authtkt_authentication_policy]
    authentication_policy = MultiAuthenticationPolicy(policies)
    config.set_authentication_policy(authentication_policy)

    config.include('pyramid_mako')
    config.include(pyramid_tm.includeme)

    config.add_static_view('static', 'static', cache_max_age=3600)

    config.add_route('home', '/')
    config.add_route('viewer', '/viewer.js')
    config.add_route('image_proxy', '/img/{type}/{id}')
    config.add_route('pdf_proxy', '/pdf/{type}/{id}.pdf')

    # historic parcels
    config.add_route('historic_parcel_get', '/historic_parcel/{id}')
    config.add_route('historic_parcel', '/historic_parcel')
    config.add_route('historic_parcel_doc', '/historic_parcel_doc')

    # print proxy routes
    config.add_route('printproxy', '/printproxy')
    config.add_route('printproxy_info', '/printproxy/info.json')
    config.add_route('printproxy_create', '/printproxy/create.json')
    config.add_route('printproxy_get', '/printproxy/{file}.printout')

    # mutation
    config.add_route('mutation_list', '/mutation/list')

    config.scan()
    return config.make_wsgi_app()
开发者ID:sitn,项目名称:historic_cadastre,代码行数:60,代码来源:__init__.py


示例6: test_add_engine_twice

 def test_add_engine_twice(self):
     db1 = sa.create_engine(self.db1.url)
     db2 = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(db1)
     self.assertIs(sqlahelper.get_session().bind, db1)
     sqlahelper.add_engine(db2)
     self.assertIs(sqlahelper.get_session().bind, db2)
     self.assertIs(sqlahelper.get_session().bind, sqlahelper.sessions.default.registry.registry.value.bind)
开发者ID:pyramid-collective,项目名称:SQLAHelper,代码行数:8,代码来源:tests.py


示例7: setUp

    def setUp(self):
        try:
            engine = sqlahelper.get_engine()
        except:  # pragma: no cover
            engine = sqlalchemy.engine_from_config({"sqlalchemy.url": "sqlite://"})
            sqlahelper.add_engine(engine)

        self._setup_pyramid()
开发者ID:WouterVH,项目名称:ptah,代码行数:8,代码来源:base.py


示例8: init_engine

def init_engine(config):
    engine = create_engine(
        config.get('SQLALCHEMY_DATABASE_URI'),
            echo=config.get('SQLALCHEMY_ECHO'),
            pool_recycle=config.get('SQLALCHEMY_POOL_RECYCLE'),
            convert_unicode=True
        )

    add_engine(engine)
开发者ID:nict-isp,项目名称:scn-admin,代码行数:9,代码来源:meta.py


示例9: main

def main(global_config, **settings):
    engine = engine_from_config(settings)
    sqlahelper.add_engine(engine)
    config = Configurator(settings=settings,
        root_factory='.models.ShirlyResource')
    config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender')
    config.include('.')
    config.scan()
    return config.make_wsgi_app()
开发者ID:rebeccaframework,项目名称:shirly,代码行数:9,代码来源:__init__.py


示例10: init_engine

def init_engine(config):
    engine = create_engine(
        config['uri'],
        echo=config['echo'],
        pool_recycle=config['pool_recycle'],
        convert_unicode=True
    )

    add_engine(engine)
开发者ID:nict-isp,项目名称:scn-admin,代码行数:9,代码来源:meta.py


示例11: setUp

    def setUp(self):
        try:
            engine = sqlahelper.get_engine()
        except:
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': 'sqlite://'})
            sqlahelper.add_engine(engine)

        self._setup_pyramid()
        self._setup_ptah()
开发者ID:WouterVH,项目名称:ptah,代码行数:10,代码来源:base.py


示例12: main

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings)
    sqlahelper.add_engine(engine)
    config = Configurator(settings=settings)
    config.include('.fainit')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app()
开发者ID:aodag,项目名称:quickblog,代码行数:11,代码来源:__init__.py


示例13: loginchange

    def loginchange(self):
        new_password = self.request.params.get('newPassword', None)
        new_password_confirm = self.request.params.get('confirmNewPassword', None)
        if new_password is None or new_password_confirm is None:
            raise HTTPBadRequest('"newPassword" and "confirmNewPassword" should be \
                   available in request params')

        # check if loggedin
        if not self.request.user:
            raise HTTPUnauthorized('bad credentials')
        if new_password != new_password_confirm:
            raise HTTPBadRequest("the new password and the new password \
                   confirmation don't match")

        u = self.request.user
        u._set_password(new_password)
        u.is_password_changed = True
        DBSession.flush()
        log.info("password changed for user: %s" % self.request.user.username)

        # handle replication
        if 'auth_replication_enabled' in self.request.registry.settings and \
                self.request.registry.settings['auth_replication_enabled'] == \
                'true':  # pragma: no cover
            try:
                log.debug("trying to find if engine set for replication exists")
                engine = sqlahelper.get_engine('replication')
            except RuntimeError:
                log.debug("engine for replication doesn't exist yet, trying \
                          to create")
                engine = engine_from_config(
                    self.request.registry.settings,
                    'sqlalchemy_replication.')
                sqlahelper.add_engine(engine, 'replication')

            DBSession2 = scoped_session(sessionmaker(bind=engine))

            dbuser_r = DBSession2.query(User).filter(User.id == self.request.user.id)
            result = dbuser_r.all()
            if len(result) == 0:
                msg = 'user not found in replication target database: %s' \
                    % self.request.user.username
                log.exception(msg)
                return HTTPBadRequest(msg)  # pragma nocover
            else:
                u_r = dbuser_r.all()[0]
                u_r._set_password(new_password)
                u_r.is_password_changed = True
                DBSession2.commit()
                log.info("password changed in replication target database \
                    for user: %s" % self.request.user.username)

        return Response('true', cache_control="no-cache")
开发者ID:pgiraud,项目名称:c2cgeoportal,代码行数:53,代码来源:entry.py


示例14: test_multiple_engines_without_default

 def test_multiple_engines_without_default(self):
     db1 = sa.create_engine(self.db1.url)
     db2 = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(db1, "db1")
     sqlahelper.add_engine(db2, "db2")
     # Can we retrieve the engines?
     self.assertIs(sqlahelper.get_engine("db1"), db1)
     self.assertIs(sqlahelper.get_engine("db2"), db2)
     # There should be no default engine
     self.assertIsNone(sqlahelper.get_session().bind)
     self.assertIsNone(sqlahelper.get_base().metadata.bind)
     self.assertIsNone(sqlahelper.get_engine())
开发者ID:pyramid-collective,项目名称:SQLAHelper,代码行数:12,代码来源:tests.py


示例15: test_multiple_engines

 def test_multiple_engines(self):
     default = sa.create_engine(self.db1.url)
     stats = sa.create_engine(self.db2.url)
     sqlahelper.add_engine(default)
     sqlahelper.add_engine(stats, "stats")
     # Can we retrieve the engines?
     self.assertIs(sqlahelper.get_engine(), default)
     self.assertIs(sqlahelper.get_engine("default"), default)
     self.assertIs(sqlahelper.get_engine("stats"), stats)
     # Are the session binding and base binding set correctly?
     self.assertIs(sqlahelper.get_session().bind, default)
     self.assertIs(sqlahelper.get_base().metadata.bind, default)
开发者ID:pyramid-collective,项目名称:SQLAHelper,代码行数:12,代码来源:tests.py


示例16: includeme

def includeme(config):
    settings = config.registry.settings

    # add default values for some global settings
    templates_dir = list(filter(
        None, settings.get('templates_dir', '').splitlines()))
    templates_dir.append('pygall:templates')
    settings['mako.directories'] = templates_dir
    if 'photos_dir' not in settings:
        settings['photos_dir'] = 'photos'
    if 'upload_dir' not in settings:
        settings['upload_dir'] = 'upload'
    allow_cdn = asbool(settings.get('allow_cdn', 'false'))
    settings['allow_cdn'] = allow_cdn
    ip.set_dest_dir(settings['photos_dir'])
    mkdir_p(settings['upload_dir'])

    init_security(settings)
    init_resources(settings)

    authentication_policy = AuthTktAuthenticationPolicy(
            settings['authtkt_secret'], callback=groupfinder)
    authorization_policy = ACLAuthorizationPolicy()

    config.add_settings(settings)
    config.set_root_factory(RootFactory)
    config.set_locale_negotiator(default_locale_negotiator)
    config.set_authentication_policy(authentication_policy)
    config.set_authorization_policy(authorization_policy)

    # initialize database
    engine = sqlalchemy.engine_from_config(settings, 'sqlalchemy.')
    sqlahelper.add_engine(engine)
    config.include(pyramid_tm.includeme)

    # formalchemy
    config.include('pyramid_formalchemy')
    config.include('fa.jquery')
    config.formalchemy_admin('admin', package='pygall',
            view='fa.jquery.pyramid.ModelView', factory=FAModelsFactory)

    # i18n
    config.add_translation_dirs('pygall:locale')

    # bind the mako renderer to other file extensions
    config.add_renderer('.mako', mako_renderer_factory)
    config.add_renderer('jsonp', JSONP(param_name='callback'))

    config.include(add_routes)
    config.include(add_views)

    config.scan('pygall')
开发者ID:bbinet,项目名称:PyGall,代码行数:52,代码来源:__init__.py


示例17: main

def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    add_engine(engine)
    session = get_session()
    Base.metadata.create_all(engine)
    with transaction.manager:
        model = MyModel(name='one', value=1)
        session.add(model)
开发者ID:jbking,项目名称:pyramid_auth_demo,代码行数:13,代码来源:initializedb.py


示例18: setUp

    def setUp(self):
        if self._init_sqla:
            try:
                engine = sqlahelper.get_engine()
            except: # pragma: no cover
                engine = sqlalchemy.engine_from_config(
                    {'sqlalchemy.url': 'sqlite://'})
                sqlahelper.add_engine(engine)

        self.init_pyramid()

        if self._init_ptah: # pragma: no cover
            self.init_ptah()
开发者ID:runyaga,项目名称:ptah,代码行数:13,代码来源:testing.py


示例19: sqla_initializing

def sqla_initializing(ev):
    url = SQLA.url
    if url:
        engine_args = {}
        if SQLA.cache:
            engine_args['execution_options'] = \
                {'compiled_cache': SQL_compiled_cache}
        try:
            engine = sqlahelper.get_engine()
        except:
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': url}, 'sqlalchemy.', **engine_args)
            sqlahelper.add_engine(engine)
开发者ID:mcdonc,项目名称:ptah,代码行数:13,代码来源:app.py


示例20: initializing

def initializing(ev):
    # auth
    if not SECURITY.secret:
        SECURITY.secret = uuid.uuid4().get_hex()

    pname = SECURITY.policy
    if pname not in ('', 'no-policy'):
        policyFactory, attrs, kw = types[pname]

        settings = []
        for attr in attrs:
            settings.append(SECURITY.get(attr))

        kwargs = {'wild_domain': False}
        for attr in kw:
            kwargs[attr] = SECURITY.get(attr)

        policy = policyFactory(*settings, **kwargs)
        config.registry.registerUtility(policy, IAuthenticationPolicy)

    if SECURITY.authorization:
        config.registry.registerUtility(
            ACLAuthorizationPolicy(), IAuthorizationPolicy)

    # mail
    smtp_mailer = SMTPMailer(
        hostname = MAIL.host,
        port = MAIL.port,
        username = MAIL.username or None,
        password = MAIL.password or None,
        no_tls = MAIL.no_tls,
        force_tls = MAIL.force_tls,
        debug_smtp = MAIL.debug)

    MAIL.Mailer = DirectMailDelivery(smtp_mailer)
    MAIL.full_from_address = formataddr((MAIL.from_name, MAIL.from_address))

    # sqla
    url = SQLA.url
    if url:
        engine_args = {}
        if SQLA.cache:
            engine_args['execution_options'] = \
                {'compiled_cache': SQL_compiled_cache}
        try:
            engine = sqlahelper.get_engine()
        except:
            engine = sqlalchemy.engine_from_config(
                {'sqlalchemy.url': url}, 'sqlalchemy.', **engine_args)
            sqlahelper.add_engine(engine)
开发者ID:blaflamme,项目名称:ptah,代码行数:50,代码来源:srvinit.py



注:本文中的sqlahelper.add_engine函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sqlahelper.get_base函数代码示例发布时间:2022-05-27
下一篇:
Python sql_select.SqlSelect类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap