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

Python declarative.declarative_base函数代码示例

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

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



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

示例1: __init__

    def __init__(self, uri='sqlite://',
                 app=None,
                 echo=False,
                 pool_size=None,
                 pool_timeout=None,
                 pool_recycle=None,
                 convert_unicode=True,
                 query_cls=BaseQuery):

        self.uri = uri
        self.info = make_url(uri)
        self.options = self._cleanup_options(
            echo=echo,
            pool_size=pool_size,
            pool_timeout=pool_timeout,
            pool_recycle=pool_recycle,
            convert_unicode=convert_unicode,
        )

        self.connector = None
        self._engine_lock = threading.Lock()
        self.session = _create_scoped_session(self, query_cls=query_cls)

        self.Model = declarative_base(cls=Model, name='Model')
        self.BaseModel = declarative_base(cls=BaseModel, name='BaseModel')

        self.Model.db, self.BaseModel.db = self, self
        self.Model.query, self.BaseModel.query = self.session.query, self.session.query

        if app is not None:
            self.init_app(app)

        _include_sqlalchemy(self)
开发者ID:rezwanulislam,项目名称:active-sqlalchemy,代码行数:33,代码来源:active_sqlalchemy.py


示例2: __init__

    def __init__(self, config):
        """
        Initializes the declarative bases that are used throughout the project.
        Initializes the empty engines and sessionmakers that support
        `get_session`, `get_mw_session` and `get_ca_session`.
        """

        self.config = config

        self.WikimetricsBase = declarative_base(cls=SerializableBase)
        self.MediawikiBase = declarative_base(cls=SerializableBase)
        self.CentralAuthBase = declarative_base(cls=SerializableBase)

        self.wikimetrics_engine = None
        self.wikimetrics_sessionmaker = None
        self.wikimetrics_session = None

        self.mediawiki_engines = {}
        self.mediawiki_sessions = {}

        self.centralauth_engine = None
        self.centralauth_sessionmaker = None
        self.centralauth_session = None

        # we instantiate project_host_map lazily
        self._project_host_map = None
开发者ID:OrenBochman,项目名称:analytics-wikimetrics,代码行数:26,代码来源:database.py


示例3: MakeClasses

def MakeClasses(metadata):
  Base = declarative_base(metadata=metadata)
  class GBID(Base):
      __tablename__ = 'gbid'
      __table_args__ = (UniqueConstraint('name'), {})
      id = Column(Integer, primary_key=True)
      name = Column(String, index = True)
      offset = Column(Integer)
      def __init__(self, name, offset):
          self.name = name
          self.offset = offset
  
  sgjBase = declarative_base(metadata = metadata)
  class GBID_SequenceJoin(sgjBase):
    __tablename__ = 'gbid_sequencejoin'
    __table_args__ = (UniqueConstraint('sequence'), {})

    id = Column(Integer, primary_key=True)
    sequence = Column(Integer, 
                      ForeignKey('sequence.id'),
                      index = True)
    gbid = Column(Integer,
                  ForeignKey('gbid.id'))
    def __init__(self, gbid, sequence):
      self.gbid = gbid
      self.sequence = sequence
  return dict(GBID = GBID, GBID_SequenceJoin = GBID_SequenceJoin)
开发者ID:bh0085,项目名称:compbio,代码行数:27,代码来源:gbid.py


示例4: MakeClasses

def MakeClasses(metadata):
  Base = declarative_base(metadata=metadata)
  class Gbfile(Base):
      __tablename__ = 'gbfile'
      __table_args__ = (UniqueConstraint('name'), {})
      id = Column(Integer, primary_key=True)
      name = Column(String, index = True)
      def __init__(self, name):
          self.name = name
  
  sgjBase = declarative_base(metadata = metadata)
  class Gbfile_GBIDJoin(sgjBase):
    __tablename__ = 'gbfile_gbidjoin'
    __table_args__ = (UniqueConstraint('gbid'), {})

    id = Column(Integer, primary_key=True)
    gbfile = Column(Integer, 
                      ForeignKey('gbfile.id'))
    gbid = Column(Integer,
                  ForeignKey('gbid.id'),
                  index = True)
    def __init__(self, gbfile, gbid):
      self.gbid = gbid
      self.gbfile = gbfile
  return dict(Gbfile = Gbfile, Gbfile_GBIDJoin = Gbfile_GBIDJoin)
开发者ID:bh0085,项目名称:compbio,代码行数:25,代码来源:gbfile.py


示例5: extended_declarative_base

def extended_declarative_base(db_session, forms=True, **kw):
    if forms:
        Base = declarative_base(cls=FormBase, **kw)
    else:
        Base = declarative_base(cls=ExtendedBase, **kw)
    Base.query = db_session.query_property()
    return Base
开发者ID:LeResKP,项目名称:sqla_declarative,代码行数:7,代码来源:declarative.py


示例6: db_connect

def db_connect(engine, schema=None, clobber=False):
    """Create a connection object to a database. Attempt to establish a
    schema. If there are existing tables, delete them if clobber is
    True and return otherwise. Returns a sqlalchemy engine object.

    """

    if schema is None:
        base = declarative_base()
    else:
        try:
            engine.execute(sqlalchemy.schema.CreateSchema(schema))
        except sqlalchemy.exc.ProgrammingError as err:
            logging.warn(err)
        base = declarative_base(metadata=MetaData(schema=schema))

    define_schema(base)

    if clobber:
        logging.info('Clobbering database tables')
        base.metadata.drop_all(bind=engine)

    logging.info('Creating database tables')
    base.metadata.create_all(bind=engine)

    return base
开发者ID:fhcrc,项目名称:taxtastic,代码行数:26,代码来源:ncbi.py


示例7: test_custom_mapper

    def test_custom_mapper(self):
        class MyExt(sa.orm.MapperExtension):
            def create_instance(self):
                return "CHECK"

        def mymapper(cls, tbl, **kwargs):
            kwargs['extension'] = MyExt()
            return sa.orm.mapper(cls, tbl, **kwargs)

        from sqlalchemy.orm.mapper import Mapper
        class MyMapper(Mapper):
            def __init__(self, *args, **kwargs):
                kwargs['extension'] = MyExt()
                Mapper.__init__(self, *args, **kwargs)

        from sqlalchemy.orm import scoping
        ss = scoping.ScopedSession(create_session)
        ss.extension = MyExt()
        ss_mapper = ss.mapper

        for mapperfunc in (mymapper, MyMapper, ss_mapper):
            base = decl.declarative_base()
            class Foo(base):
                __tablename__ = 'foo'
                __mapper_cls__ = mapperfunc
                id = Column(Integer, primary_key=True)
            eq_(Foo.__mapper__.compile().extension.create_instance(), 'CHECK')

            base = decl.declarative_base(mapper=mapperfunc)
            class Foo(base):
                __tablename__ = 'foo'
                id = Column(Integer, primary_key=True)
            eq_(Foo.__mapper__.compile().extension.create_instance(), 'CHECK')
开发者ID:jrus,项目名称:sqlalchemy,代码行数:33,代码来源:declarative.py


示例8: MakeClasses

def MakeClasses(metadata):

  Base = declarative_base(metadata=metadata)
  class Alignment(Base):
    __tablename__ = 'alignment'
    __table_args__ = (UniqueConstraint('name'), {})

    id = Column(Integer, primary_key=True)
    source = Column(String)
    name = Column(String)
    def __init__(self, source = 'None'):
        self.source = source

  asjBase = declarative_base(metadata = metadata)
  class Alignment_SequenceJoin(asjBase):
    __tablename__= 'alignment_sequencejoin'
    __table_args__ = (UniqueConstraint('sequence'), {})    
    id = Column(Integer, primary_key=True)
    alignment = Column(Integer, 
                       ForeignKey('alignment.id'))
    sequence = Column(Integer,
                      ForeignKey('sequence.id'))
    def __init__(self, alignment, sequence):
      self.alignment = alignment
      self.sequence = sequence
  return dict(Alignment = Alignment, Alignment_SequenceJoin = Alignment_SequenceJoin)
开发者ID:bh0085,项目名称:compbio,代码行数:26,代码来源:alignment.py


示例9: declarative_bases

def declarative_bases(metadata, registry=None):
    """Return all declarative bases bound to a single metadata object."""
    if registry is None:
        registry = dict()
    return (declarative_base(cls=BaseOps, metadata=metadata,
                             class_registry=registry),
            declarative_base(cls=Timestamped, metadata=metadata,
                             class_registry=registry))
开发者ID:hellsingblack,项目名称:assembl,代码行数:8,代码来源:sqla.py


示例10: test_other_base_twice__different

 def test_other_base_twice__different(self):
     Base = declarative_base()
     Base2 = declarative_base()
     contract = {"Group": {"table_name": "groups"}}
     models1 = self._callFUT(Base, contract)
     models2 = self._callFUT(Base2, contract)
     self.assertNotEqual(models1, models2)
     self.assertNotEqual(models1.Group, models2.Group)
开发者ID:podhmo,项目名称:sqlaqb,代码行数:8,代码来源:test_it_directly.py


示例11: test_create_drop_tables_several_meta

    def test_create_drop_tables_several_meta(self):
        Base1 = declarative_base()

        class A1(Base1):
            __tablename__ = 'A'
            id = Column(Integer, primary_key=True)

        Base2 = declarative_base()

        class A2(Base2):
            __tablename__ = 'A'
            id = Column(Integer, primary_key=True)

        engine1 = create_engine('sqlite://')
        engine2 = create_engine('sqlite://')
        binds = {
            A1.__table__: engine1,
            A2.__table__: engine2,
        }
        meta = {
            'm1': Base1.metadata,
            'm2': Base2.metadata,
            'm3': MetaData(),
        }
        cli = Sqla(orm.sessionmaker(binds=binds), metadata=meta)

        for verbose in [False, True]:

            cli.command_create_tables(verbose=verbose)
            self.assertTrue(engine1.has_table('A'))
            self.assertTrue(engine2.has_table('A'))

            with mock.patch.object(sys.stdin, 'readline', return_value='y'):
                cli.command_drop_tables('m1')
            self.assertFalse(engine1.has_table('A'))
            self.assertTrue(engine2.has_table('A'))

            with mock.patch.object(sys.stdin, 'readline', return_value='y'):
                cli.command_drop_tables()
            self.assertFalse(engine1.has_table('A'))
            self.assertFalse(engine2.has_table('A'))

            cli.command_create_tables('m1', verbose=verbose)
            self.assertTrue(engine1.has_table('A'))
            self.assertFalse(engine2.has_table('A'))

            with mock.patch.object(sys.stdin, 'readline', return_value='y'):
                cli.command_drop_tables()
            self.assertFalse(engine1.has_table('A'))
            self.assertFalse(engine2.has_table('A'))

            cli.command_create_tables('m3', verbose=verbose)
            self.assertFalse(engine1.has_table('A'))
            self.assertFalse(engine2.has_table('A'))
开发者ID:oas89,项目名称:iktomi,代码行数:54,代码来源:sqla.py


示例12: __init__

 def __init__(self, config: DBConfig) -> None:
     self.engine = create_engine(config.URI)
     self.engine.echo = config.ECHO
     self.Model = declarative_base()
     self.Model.metadata.bind = self.engine
     self.__DBSession = sessionmaker(bind=self.engine)
     self.session = self.__DBSession()
开发者ID:CzarSimon,项目名称:mimir,代码行数:7,代码来源:database.py


示例13: make_declarative_base

 def make_declarative_base(self):
     """Creates the declarative base."""
     base = declarative_base(cls=Model, name='Model',
                             mapper=signalling_mapper,
                             metaclass=_BoundDeclarativeMeta)
     base.query = _QueryProperty(self)
     return base
开发者ID:EnTeQuAk,项目名称:flask-sqlalchemy,代码行数:7,代码来源:sqlalchemy.py


示例14: table_base

    def table_base(self):
        """Base class for all tables returned by this database

        This base class is created using
        :py:class:`declarative_base <sqlalchemy:sqlalchemy.ext.declarative.declarative_base>`.
        """
        return declarative_base(metadata=self.metadata)
开发者ID:FilipB,项目名称:cfme_tests,代码行数:7,代码来源:db.py


示例15: __init__

    def __init__(self):
        #self.engine = create_engine('sqlite://///home/weis/code/baltic_rallye_code/common/sequences.db')
        self.engine = create_engine('sqlite://///home/pi/baltic_rallye_code/common/sequences.db')
        #self.engine = create_engine('sqlite://///home/weis/Desktop/baltic_rallye_code/common/sequences.db')
        #self.engine = create_engine('sqlite://///home/weis/code/gpslapse/common/sequences.db')

        self.base = declarative_base()
        self.meta = MetaData(bind=self.engine)
        Session = sessionmaker(bind=self.engine)
        self.session = Session()

        # first, get meta-data (structure and datatypes from all tables
        self.sequences = Table('sequences', self.meta, autoload=True, autoload_with=self.engine)
        self.sensors = Table('sensors', self.meta, autoload=True, autoload_with=self.engine)
        self.frames = Table('frames', self.meta, autoload=True, autoload_with=self.engine)
        self.annot_cars = Table('annot_cars', self.meta, autoload=True, autoload_with=self.engine)
        self.annot_taillights = Table('annot_taillights', self.meta, autoload=True, autoload_with=self.engine)

        # now, map the dummy-classes above to the tables, they inherit all fields
        # and can be used to insert or query from the database
        orm.mapper(self.Sensor, self.sensors)
        orm.mapper(self.Sequence, self.sequences)
        orm.mapper(self.Frame, self.frames)
        orm.mapper(self.AnnotCar, self.annot_cars)
        orm.mapper(self.AnnotTaillight, self.annot_taillights)
开发者ID:TobiasWeis,项目名称:gpslapse,代码行数:25,代码来源:DBInterface.py


示例16: Init

def Init():
	global Base,metadata,engine,Session
	Base=declarative_base()
	metadata=MetaData()
	engine=create_engine(cp.Connect_string,pool_size=cp.dbpoolsize,max_overflow=0,pool_timeout=cp.dbpool_timeout,pool_recycle=cp.dbpool_recycle,echo=cp.dbecho)
	Session = sessionmaker(bind=engine)
	metadata.reflect(bind=engine)
开发者ID:CheeponLee,项目名称:atplatform,代码行数:7,代码来源:sharedobject.py


示例17: define_tables

        def define_tables(self, metadata):
            global User, Address
            Base = decl.declarative_base(metadata=metadata)

            class User(Base, ComparableEntity):
                __tablename__ = 'users'
                id = Column(Integer, primary_key=True)
                name = Column(String(50))
            
            class Address(Base, ComparableEntity):
                __tablename__ = 'addresses'
                id = Column(Integer, primary_key=True)
                email = Column(String(50))
                user_id = Column(Integer, ForeignKey('users.id'))
                if inline:
                    if stringbased:
                        user = relation("User", primaryjoin="User.id==Address.user_id", backref="addresses")
                    else:
                        user = relation(User, primaryjoin=User.id==user_id, backref="addresses")
            
            if not inline:
                compile_mappers()
                if stringbased:
                    Address.user = relation("User", primaryjoin="User.id==Address.user_id", backref="addresses")
                else:
                    Address.user = relation(User, primaryjoin=User.id==Address.user_id, backref="addresses")
开发者ID:jrus,项目名称:sqlalchemy,代码行数:26,代码来源:declarative.py


示例18: upgrade

def upgrade():
    if 'easfoldersyncstatus' in Base.metadata.tables:
        from inbox.ignition import main_engine
        engine = main_engine(pool_size=1, max_overflow=0)
        from inbox.models.session import session_scope
        from sqlalchemy.ext.declarative import declarative_base
        from sqlalchemy.orm.exc import NoResultFound
        Base = declarative_base()
        Base.metadata.reflect(engine)
        from inbox.models.backends.eas import EASFolderSyncStatus
        from inbox.models import Folder
        from inbox.util.eas.constants import SKIP_FOLDERS

        with session_scope(versioned=False, ignore_soft_deletes=False) as \
                db_session:
            statuses = db_session.query(EASFolderSyncStatus).filter(
                EASFolderSyncStatus.eas_folder_type.in_(SKIP_FOLDERS)).all()
            for s in statuses:
                db_session.delete(s)
                db_session.delete(s.folder)

            try:
                for status in db_session.query(EASFolderSyncStatus)\
                        .join(Folder).filter(
                            Folder.name == 'RecipientInfo').all():
                    db_session.delete(status)
                    db_session.delete(status.folder)
            except NoResultFound:
                pass

            db_session.commit()
开发者ID:0xcd03,项目名称:inbox,代码行数:31,代码来源:061_remove_easfoldersyncstatus_folder_rows_.py


示例19: dummy_mapper

def dummy_mapper(table):
    Base = declarative_base()

    class DummyMapper(Base):
        __table__ = table

    return DummyMapper
开发者ID:piojo,项目名称:aquilon,代码行数:7,代码来源:aqdb_migrate.py


示例20: test_custom_base

 def test_custom_base(self):
     class MyBase(object):
         def foobar(self):
             return "foobar"
     Base = decl.declarative_base(cls=MyBase)
     assert hasattr(Base, 'metadata')
     assert Base().foobar() == "foobar"
开发者ID:jrus,项目名称:sqlalchemy,代码行数:7,代码来源:declarative.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python declarative.DeclarativeMeta类代码示例发布时间:2022-05-27
下一篇:
Python baked.bakery函数代码示例发布时间: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