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

Python api.declarative_base函数代码示例

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

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



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

示例1: main

def main(keep_saved, config_location):
    if not config_location:
        config_location = os.path.dirname(os.path.abspath(__file__)) + "\\config.ini"
    try:
        open(config_location)
    except IOError:
        print "Problem opening config.ini at " + config_location
    engine = create_engine(make_connection(config_location), echo=False)
    Session = sessionmaker(bind=engine)
    session = Session()

    Base = declarative_base()

    class FeverItems(Base):
        __tablename__ = 'fever_items'

        id = Column(INTEGER, primary_key=True)
        description = Column(LONGTEXT)
        is_saved = Column(TINYINT)

    records = session.query(FeverItems.description).filter_by(is_saved=1)
    contents = []
    for record in records:
        contents.append(record)
    if not keep_saved:
    session.query(FeverItems).filter_by(is_saved=1).update({"is_saved": 0})
    session.commit()
    return contents


if __name__ == "__main__":
    main(bool(sys.argv[1]), str(sys.argv[2]))
开发者ID:fuzzmz,项目名称:fever_saved_download,代码行数:32,代码来源:sql_connect.py


示例2: prepare_schema_connection

def prepare_schema_connection(model_cls, config_cls):
    model_cls.SCHEMA = config_cls.SCHEMA
    class Base(object):
        __table_args__ = {'schema': config_cls.SCHEMA, 'extend_existing':True}

    model_cls.Base = declarative_base(cls=Base)
    model_cls.metadata = model_cls.Base.metadata
    engine = create_engine("%s://%s:%[email protected]%s/%s" % (config_cls.DBTYPE, config_cls.DBUSER, config_cls.DBPASS, config_cls.DBHOST, config_cls.DBNAME), convert_unicode=True, pool_recycle=3600)
    model_cls.Base.metadata.bind = engine
    session_maker = sessionmaker(bind=engine)
        
    return session_maker
开发者ID:kpaskov,项目名称:PerfConversion,代码行数:12,代码来源:__init__.py


示例3: prepare_schema_connection

def prepare_schema_connection(model_cls, dbtype, dbhost, dbname, schema, dbuser, dbpass):
    class Base(object):
        __table_args__ = {'schema': schema, 'extend_existing':True}

    model_cls.Base = declarative_base(cls=Base)
    model_cls.Base.schema = schema
    model_cls.metadata = model_cls.Base.metadata
    engine_key = "%s://%s:%[email protected]%s/%s" % (dbtype, dbuser, dbpass, dbhost, dbname)
    engine = create_engine(engine_key, pool_recycle=3600)
    model_cls.Base.metadata.bind = engine
    session_maker = sessionmaker(bind=engine)

    return session_maker
开发者ID:kkarra,项目名称:SGDBackend,代码行数:13,代码来源:__init__.py


示例4: init_declarative_base

def init_declarative_base(override_base=None):
    global Base
    if override_base:
        Base=override_base
    else:
        Base = declarative_base()
开发者ID:aGu2ti,项目名称:gamification-engine,代码行数:6,代码来源:metadata.py


示例5: declarative_base

import sqlalchemy as sa
from wsgiref.simple_server import make_server
from pyramid.config import Configurator

from sqlalchemy import engine_from_config
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative.api import declarative_base

from seth import db
from seth.db.base import Model
from seth.classy.rest import generics


Base = declarative_base(cls=Model)


# Basic model definition
class SuperModel(Base):
    string_column = sa.Column(sa.String(512))

    def __repr__(self):
        return u"SuperModel {0}".format(self.id)


class SampleResource(generics.GenericApiView):

    def get(self):
        print SuperModel.query.count()
        SuperModel.query.all()
开发者ID:turkus,项目名称:seth,代码行数:30,代码来源:listener.py


示例6: BaseCFG

class BaseCFG(object):
    """
    Class that contains custom configuration for a
    :func:`sqlalchemy.ext.declarative.declarative_base` to be used with the
    ORM. It automatically figures out a tablename (thus no need to set
    ``__tablename__``).
    """

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

    def __str__(self):
        return unicode(self).encode("utf-8")

Base = declarative_base(cls=BaseCFG)
"""Base class for all ORM classes. Uses :class:`BaseCFG` configuration."""


class RootFactory(object):
    """Skeleton for simple ACL permission protection."""

    def __init__(self, request):
        self.request = request

    def __acl__(self):
        from .settings import CTF_BEFORE, CTF_STARTED, CTF_ARCHIVE, CTF_ENDED
        permission_map = {
            CTF_BEFORE: [
                ('group:team', ['teams', 'logged_in']),
                (Everyone, ['teams', 'login', 'register']),
开发者ID:Immortalem,项目名称:fluxscoreboard,代码行数:31,代码来源:__init__.py


示例7: create_engine

from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.schema import Column, Sequence
from sqlalchemy.types import Integer, String, DateTime


#definicao do banco de dados
DATABASE="sqlite:///blog.db"
engine = create_engine(DATABASE, echo=True)
BASE = declarative_base(engine)


class Post(BASE):
    """ modelo de post """
    __tablename__ = 'posts'
    id = Column(Integer, Sequence('post_id_seq'), primary_key=True)
    title = Column(String(250))
    content = Column(String())
    date=Column(DateTime())

    def __init__(self, title, content, date):
        self.title = title
        self.content = content
        self.date = date

    def __repr__(self):
        return "<User('%s','%s', '%s')>" % (self.id, self.title, self.date)

#essa linha roda na primeira vez que o modulo eh carregado e apenas uma vez
BASE.metadata.create_all(engine)
开发者ID:eduardocl,项目名称:pyblog,代码行数:30,代码来源:post.py


示例8: get_base_meta_class

 def get_base_meta_class(module):
     return declarative_base().__class__
开发者ID:yankyn,项目名称:ipuyol,代码行数:2,代码来源:parser.py


示例9: scoped_session

from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.orm.session import sessionmaker
from sqlalchemy.sql.schema import Column
from sqlalchemy.sql.sqltypes import Integer, String, DateTime, Text
import datetime


DBSession = scoped_session(sessionmaker())
Base = declarative_base()


class JobModel(Base):
    __tablename__ = 'jobs'
    id = Column(Integer, primary_key=True)

    city = Column(String(100), nullable=False)
    companyLogo = Column(String(150))
    companySize = Column(String(30))
    companyName = Column(String(30), nullable=False)
    industryField = Column(String(30))
    financeStage = Column(String(30))
    website = Column(String(50))

    salary = Column(String(30), nullable=False)
    jobNature = Column(String(50))
    createTime = Column(DateTime,
                        default=datetime.datetime.now,
                        nullable=False)
    positionName = Column(String(30), nullable=False)
    positionType = Column(String(30))
开发者ID:songrgg,项目名称:crawljobs,代码行数:31,代码来源:mysqlmodel.py


示例10: not

#if no env variable has been defined, a default one is set
if not(os.environ.has_key("SUBDB")):
    os.environ['SUBDB'] = 'mysql://root:[email protected]:3306/sub_ai'

URLS = {
    'SQL':os.environ['SUBDB'],
}

#print message or not
parser = argparse.ArgumentParser()
parser.add_argument('-v','--verbose',action='store_true')
parser.add_argument('-a','--alerts',action='store_true')
args = parser.parse_args()

if args.verbose:
    logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG)
else:
    logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.WARNING)

try:
    engine = sqlalchemy.create_engine(URLS['SQL'])
    Session = sessionmaker(bind=engine)
    Base = declarative_base(bind=engine)
    DBSession = sessionmaker(bind = engine)
    Base.metadata.create_all(engine)
except Exception:
    logging.error('Database is not reachable with provided path : %s',URLS['SQL'])
    logging.error('Please check database instance is running and database name exists')
    exit(0)    
开发者ID:subena-io,项目名称:subena,代码行数:29,代码来源:base.py


示例11: declarative_base

from sqlalchemy import Column, types
import datetime

from mittn.issue import Issue
from sqlalchemy.ext.declarative.api import declarative_base

import json

import socket
HOSTNAME = socket.gethostbyname(socket.gethostname())

Base = declarative_base(cls=Issue)
class ScannerIssue(Base):
    __tablename__ = 'headlessscanner_issues'

    # We use LargeBinary in message because it can be very big

    # XXX fields that are used in all tools come from issue.py

    severity = Column(types.Text)
    issuetype = Column(types.Text)
    issuename = Column(types.Text)
    issuedetail = Column(types.Text)
    confidence = Column(types.Text)
    host = Column(types.Text)
    port = Column(types.Text)
    protocol = Column(types.Text)
    messages = Column(types.LargeBinary)

    def unique_fields(self):
        """ These fields are used when checking for false
开发者ID:praetoria,项目名称:mittn,代码行数:31,代码来源:scannerissue.py


示例12: declarative_base

from sqlalchemy.ext.declarative.api import declarative_base

vxlan_id = -1
vm_id = 0

BASEOBJ = declarative_base()

class base(BASEOBJ):
    """Base class for Nova and Glance Models"""
    __abstract__ = True
    __table_args__ = {'mysql_engine': 'InnoDB'}
    __table_initialized__ = False

class test(base):
    """ Base class for resource type object """
    __abstract__ = True

    _resource_name_ = None
    _alias_name_ = None

    __protected_attributes__ = set([
        "created_at", "updated_at", "deleted_at", "deleted"])

class g_var(object):
    def __init__(self):
        global vxlan_id
        pass

    @classmethod
    def print_cls(cls):
        print cls.__class__
开发者ID:Shouren,项目名称:snippet,代码行数:31,代码来源:cls.py


示例13: create_engine

from sqlalchemy import *
from sqlalchemy.orm import relationship, backref
from sqlalchemy.schema import Column, Sequence, PrimaryKeyConstraint, ForeignKey
from sqlalchemy.types import Integer, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm.session import sessionmaker

engine = create_engine("sqlite:///development.sqlite3", echo=False)
Base = declarative_base(engine)


documents_tags = Table(
    "documents_tags",
    Base.metadata,
    Column("document_id", Integer, ForeignKey("documents.id")),
    Column("tag_id", Integer, ForeignKey("tags.id")),
)


authors_documents = Table(
    "authors_documents",
    Base.metadata,
    Column("author_id", Integer, ForeignKey("authors.id")),
    Column("document_id", Integer, ForeignKey("documents.id")),
)


class Document(Base):
    __tablename__ = "documents"
    id = Column(Integer, Sequence("document_id_seq"), primary_key=True)
开发者ID:eduardocl,项目名称:rkb,代码行数:31,代码来源:rkb-python.py


示例14: declarative_base

import os

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker

from eventsourcing.infrastructure.datastore import Datastore, DatastoreConnectionError, DatastoreSettings

ActiveRecord = declarative_base()

DEFAULT_SQLALCHEMY_DB_URI = 'sqlite:///:memory:'


class SQLAlchemySettings(DatastoreSettings):
    DB_URI = os.getenv('DB_URI', DEFAULT_SQLALCHEMY_DB_URI)

    def __init__(self, uri=DEFAULT_SQLALCHEMY_DB_URI):
        self.uri = uri or self.DB_URI


class SQLAlchemyDatastore(Datastore):

    def __init__(self, base=ActiveRecord, tables=None, connection_strategy='plain',
                 # connect_args=None, poolclass=None,
                 **kwargs):
        super(SQLAlchemyDatastore, self).__init__(**kwargs)
        self._session = None
        self._engine = None
        self._base = base
        self._tables = tables
        self._connection_strategy = connection_strategy
开发者ID:julianpistorius,项目名称:eventsourcing,代码行数:31,代码来源:datastore.py


示例15: declarative_base

from sqlalchemy.ext.declarative.api import declarative_base
from puyol.orm.query import PuyolQuery

__author__ = 'USER'

AlchemyBase = declarative_base()


class Base(object):

    @classmethod
    def get(cls, *criteria, **kwargs):
        from puyol.connector import session
        return PuyolQuery(session.query(cls), cls, *criteria, **kwargs)
开发者ID:yankyn,项目名称:puyol,代码行数:14,代码来源:base.py


示例16: __tablename__


    @declared_attr
    def __tablename__(self):
        if has_inherited_table(self):
            return None
        name = self.__name__
        return (
            name[0].lower() +
            re.sub(r'([A-Z])', lambda m:"_" + m.group(0).lower(), name[1:])
        )
        
    __table_args__ = {'mysql_engine': 'InnoDB'}


Base = declarative_base(cls=_Base_)


def connect(url):
    engine = create_engine(url)
    Session = sessionmaker(autocommit=False,
                           autoflush=False,
                           bind=engine)
    return Session
    
    
def create_all(engine):
    Base.metadata.create_all(engine)
    

def drop_all(session):
开发者ID:OliverDashiell,项目名称:Puzzled,代码行数:29,代码来源:base.py


示例17: create_engine

from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.schema import Column
from sqlalchemy.sql.sqltypes import Integer, CHAR


DB_CONNECT_STRING = 'mysql://root:[email protected]:3306/test?charset=utf8&use_unicode=1'
params = {'pool_recycle': 60, 'echo_pool': True, 'pool_size': 500, 'echo': True}

engine = create_engine(DB_CONNECT_STRING, *(), **params)
# engine = create_engine(DB_CONNECT_STRING)
DB_Session = sessionmaker(bind=engine)
session = DB_Session()

# declarative_base() 创建了一个 BaseModel 类,这个类的子类可以自动与一个表关联。
BaseModel = declarative_base()

class User(BaseModel):
    __tablename__ = 'user'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', CHAR(30)) # or Column(String(30))



def init_db():
    # BaseModel.metadata.create_all(engine) 会找到 BaseModel 的所有子类,并在数据库中建立这些表;
    BaseModel.metadata.create_all(engine)
def drop_db():
    BaseModel.metadata.drop_all(engine)

init_db()
开发者ID:prestonTao,项目名称:python-example,代码行数:31,代码来源:sqlalchemy_00020.py


示例18: declarative_base

from wsgiref.simple_server import make_server

import sqlalchemy as sa
from sqlalchemy import engine_from_config
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative.api import declarative_base
from zope.sqlalchemy import ZopeTransactionExtension
from marshmallow import Schema, fields

from seth import db
from seth import filtering
from seth.classy.rest import generics
from seth.db.base import TimeStampedModel


Base = declarative_base(cls=TimeStampedModel)


# Basic model definition
class SuperModel(Base):
    string_column = sa.Column(sa.String(512))


# Define model filter
class SuperModelFilters(filtering.FilterFactory):
    model = SuperModel
    string_column = filtering.CharFilter()


# Basic schema definition - TimeStampedModel predefines four fields:
# id, is_deleted, created_at, updated_at
开发者ID:turkus,项目名称:seth,代码行数:31,代码来源:api.py


示例19: create_engine

from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm.session import sessionmaker
from sqlalchemy.types import Integer, Float, String
from tempfile import NamedTemporaryFile, mkdtemp
import sys
import re
import os
import shutil


#connstr = 'sqlite://'
## four slashes for absolute paths - three for relative
connstr = 'sqlite:///{0}'.format('/tmp/profile.sqlite')
engine = create_engine(connstr)
metadata = MetaData(bind=engine)
Base = declarative_base(metadata=metadata)
Session = sessionmaker(bind=engine)


class Results(Base):
    __tablename__ = 'results'
    rid = Column(Integer,primary_key=True)
    ncalls = Column(Integer)
    tottime = Column(Float)
    filename = Column(String)
    percall_tottime = Column(Float)
    cumtime = Column(Float)
    percall_cumtime = Column(Float)
    
    
class ExecutionInfo(Base):
开发者ID:HydroLogic,项目名称:ocgis,代码行数:31,代码来源:profile.py


示例20: declarative_base

"""
Created on Nov 29, 2013

@author: be07336
"""
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, String, NUMERIC
from model.connection import ConnectionManager

Base = declarative_base(bind=ConnectionManager.get_instance().get_engine())


class Candidate(Base):
    """
    Candidate class
    """

    __tablename__ = 'CANDIDATE'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)
    year = Column(String)
    destination = Column(String)
    company = Column(String)

    evaluations = relationship("Evaluation", primaryjoin="Candidate.id == Evaluation.candidate")

    others = relationship("Document", primaryjoin="and_(Candidate.id == Document.candidate,"
开发者ID:cfroment,项目名称:py-bsse-2016,代码行数:31,代码来源:candidate.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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