本文整理汇总了Python中sqlalchemy.ext.declarative.DeclarativeMeta方法的典型用法代码示例。如果您正苦于以下问题:Python declarative.DeclarativeMeta方法的具体用法?Python declarative.DeclarativeMeta怎么用?Python declarative.DeclarativeMeta使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.ext.declarative
的用法示例。
在下文中一共展示了declarative.DeclarativeMeta方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decode
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def decode(obj):
if obj and isinstance(obj.__class__, DeclarativeMeta):
fields = {}
for field in [x for x in dir(obj) if not x.startswith('_') and not x.endswith('_') and x != 'metadata']:
data = obj.__getattribute__(field)
if isinstance(data, datetime.datetime):
fields[field] = data.timestamp()
elif isinstance(data, datetime.date):
fields[field] = data.isoformat()
elif isinstance(data, datetime.timedelta):
fields[field] = (datetime.datetime.min + data).time().isoformat()
elif isinstance(data, int) or isinstance(data, float) or isinstance(data, str):
fields[field] = data
elif isinstance(data, enum.Enum):
fields[field] = data.value
elif isinstance(data.__class__, DeclarativeMeta):
fields[field] = AlchemyEncoder.decode(data)
elif isinstance(data, list):
fields[field] = [AlchemyEncoder.decode(d) for d in data]
return fields
else:
return obj
示例2: __init__
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def __init__(
self,
settings: SQLAlchemySettings,
base: DeclarativeMeta = Base,
tables: Optional[Sequence] = None,
connection_strategy: str = "plain",
session: Optional[Union[Session, scoped_session]] = None,
):
super(SQLAlchemyDatastore, self).__init__(settings=settings)
self._was_session_created_here = False
self._session = session
if session:
self._engine: Optional[Engine] = session.get_bind()
else:
self._engine = None
self._base = base
self._tables = tables
self._connection_strategy = connection_strategy
示例3: get_schemas
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def get_schemas(provider: str) -> List[DeclarativeMeta]:
"""
get domain schemas supported by the provider
:param provider:
:type provider:
:return:
:rtype:
"""
schemas = []
for provider1, dbs in zvt_context.provider_map_dbnames.items():
if provider == provider1:
for dbname in dbs:
schemas1 = zvt_context.dbname_map_schemas.get(dbname)
if schemas1:
schemas += schemas1
return schemas
示例4: __init__
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def __init__(self, model: DeclarativeMeta, writable_properties=True, **handler_settings):
""" Init CRUD helper
:param model: The model to work with
:param handler_settings: Settings for the MongoQuery used to make queries
"""
self.model = model
self.handler_settings = handler_settings
self.bags = self._MODEL_PROPERTY_BAGS_CLS.for_model(model)
self.reusable_mongoquery = Reusable(self._MONGOQUERY_CLS(self.model, handler_settings)) # type: MongoQuery
# Settings
self.writable_properties = writable_properties
# We also need `legacy_fields`
# we're going to ignore them in the input
self.legacy_fields = self.reusable_mongoquery.handler_project.legacy_fields
示例5: for_model
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def for_model(cls, model: DeclarativeMeta) -> 'ModelPropertyBags':
""" Get bags for a model.
Please use this method over __init__(), because it initializes those bags only once
"""
# The goal of this method is to only initialize a ModelPropertyBags only once per model.
# Previously, we used to store them inside model attributes.
try:
# We want ever model class to have its own ModelPropertyBags,
# and we want no one to inherit it.
# We could use model.__dict__ for this, but classes in Python 3 use an immutable `mappingproxy` instead.
# Thus, we have to keep our own cache of ModelPropertyBags.
return cls.__bags_per_model_cache[model]
except KeyError:
cls.__bags_per_model_cache[model] = bags = cls(model)
return bags
示例6: __init__
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def __init__(self,
Model: DeclarativeMeta,
entity_dict: dict,
*,
ordinal_number: int = None,
pk_names: Sequence[str] = None):
super().__init__(entity_dict)
self.Model = Model
self.ordinal_number = ordinal_number
# Primary key names: use the provided list; get it ourselves if not provided
if not pk_names:
_, pk_names = model_primary_key_columns_and_names(Model)
# The primary key tuple
try:
self.primary_key_tuple = tuple(entity_dict[pk_field]
for pk_field in pk_names)
self.has_primary_key = True
# If any of the primary key fields has raised a KeyError, assume that no PK is defined
except KeyError:
self.has_primary_key = False
self.primary_key_tuple = None
示例7: validate_related_settings
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def validate_related_settings(self, bags: mongosql.ModelPropertyBags):
""" Validate the settings for related entities.
This method only validates the keys for "related" and "related_models".
:raises KeyError: Invalid keys
"""
# Validate "related": all keys must be relationship names
invalid_keys = set(self._nested_relation_settings.keys()) - bags.relations.names - {'*'}
if invalid_keys:
raise KeyError('Invalid relationship name provided to "related": {!r}'
.format(list(invalid_keys)))
# Validated "related_models": all keys must be models, not names
invalid_keys = set(v
for v in self._nested_model_settings.keys()
if not isinstance(v, DeclarativeMeta))
invalid_keys -= {'*'}
if invalid_keys:
raise KeyError('Invalid related model object provided to "related_models": {!r}'
.format(list(invalid_keys)))
示例8: default
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def default(self, o):
if isinstance(o, datetime.datetime):
# d = datetime_safe.new_datetime(o)
# return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
elif isinstance(o, datetime.date):
# d = datetime_safe.new_date(o)
return o.strftime(self.DATE_FORMAT)
elif isinstance(o, datetime.time):
return o.strftime(self.TIME_FORMAT)
elif isinstance(o, decimal.Decimal):
return str(o)
elif isinstance(o, ResultProxy):
return list(o)
elif isinstance(o, RowProxy):
return dict(o)
elif isinstance(o.__class__, DeclarativeMeta):
fields = {}
instance_dict = o.__dict__
for field in instance_dict:
if not field.startswith('_'):
fields[field] = instance_dict[field]
return fields
else:
return super(AwareJSONEncoder, self).default(o)
示例9: to_dict
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def to_dict(self, rel=None, backref=None):
if rel is None:
rel = self.RELATIONSHIPS_TO_DICT
res = {column.key: getattr(self, attr)
for attr, column in self.__mapper__.c.items()}
if rel:
for attr, relation in self.__mapper__.relationships.items():
# Avoid recursive loop between to tables.
if backref == relation.table:
continue
value = getattr(self, attr)
if value is None:
res[relation.key] = None
elif isinstance(value.__class__, DeclarativeMeta):
res[relation.key] = value.to_dict(backref=self.__table__)
else:
res[relation.key] = [i.to_dict(backref=self.__table__)
for i in value]
return res
示例10: to_dict
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def to_dict(self, rel=None, backref=None):
if rel is None:
rel = self.RELATIONSHIPS_TO_DICT
res = {
column.key: self.custom_encoding(attr)
for attr, column in self.__mapper__.c.items()
}
if self.__mapper__.relationships.items():
for attr, relation in self.__mapper__.relationships.items():
# Avoid recursive loop between to tables.
if backref == relation.table:
continue
value = getattr(self, attr)
if value is None:
res[relation.key] = None
elif isinstance(value.__class__, DeclarativeMeta):
res[relation.key] = value.to_dict(backref=self.__table__)
else:
res[relation.key] = [
i.to_dict(backref=self.__table__) for i in value
]
return res
示例11: sqlalchemy_user_db
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def sqlalchemy_user_db() -> AsyncGenerator[SQLAlchemyUserDatabase, None]:
Base: DeclarativeMeta = declarative_base()
class User(SQLAlchemyBaseUserTable, Base):
first_name = Column(String, nullable=True)
DATABASE_URL = "sqlite:///./test-sqlalchemy-user.db"
database = Database(DATABASE_URL)
engine = sqlalchemy.create_engine(
DATABASE_URL, connect_args={"check_same_thread": False}
)
Base.metadata.create_all(engine)
await database.connect()
yield SQLAlchemyUserDatabase(UserDB, database, User.__table__)
Base.metadata.drop_all(engine)
示例12: sqlalchemy_user_db_oauth
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def sqlalchemy_user_db_oauth() -> AsyncGenerator[SQLAlchemyUserDatabase, None]:
Base: DeclarativeMeta = declarative_base()
class User(SQLAlchemyBaseUserTable, Base):
first_name = Column(String, nullable=True)
class OAuthAccount(SQLAlchemyBaseOAuthAccountTable, Base):
pass
DATABASE_URL = "sqlite:///./test-sqlalchemy-user-oauth.db"
database = Database(DATABASE_URL)
engine = sqlalchemy.create_engine(
DATABASE_URL, connect_args={"check_same_thread": False}
)
Base.metadata.create_all(engine)
await database.connect()
yield SQLAlchemyUserDatabase(
UserDBOAuth, database, User.__table__, OAuthAccount.__table__
)
Base.metadata.drop_all(engine)
示例13: get_db_name
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def get_db_name(data_schema: DeclarativeMeta) -> str:
"""
get db name of the domain schema
:param data_schema:
:type data_schema:
:return:
:rtype:
"""
for db_name, base in zvt_context.dbname_map_base.items():
if issubclass(data_schema, base):
return db_name
示例14: table_name_to_domain_name
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def table_name_to_domain_name(table_name: str) -> DeclarativeMeta:
"""
the rules for table_name -> domain_class
:param table_name:
:type table_name:
:return:
:rtype:
"""
parts = table_name.split('_')
domain_name = ''
for part in parts:
domain_name = domain_name + part.capitalize()
return domain_name
示例15: get_schema_by_name
# 需要导入模块: from sqlalchemy.ext import declarative [as 别名]
# 或者: from sqlalchemy.ext.declarative import DeclarativeMeta [as 别名]
def get_schema_by_name(name: str) -> DeclarativeMeta:
"""
get domain schema by the name
:param name:
:type name:
:return:
:rtype:
"""
for schema in zvt_context.schemas:
if schema.__name__ == name:
return schema