未提供项目说明
lc-sqlalchemy-dbutils的Python项目详细描述
SqlDbChempy公司
概述
SQLAlchemy有两个高级组件:Core和ORM。核心提供(毫不奇怪)
SQLAlchemy的SQL抽象层的核心功能。ORM(“Object-Relational Mapper”)组件提供
在Python和数据库类型之间映射的能力。sqlalchemy-dbutils-py
提供了许多基于此构建的实用程序
ORM组件,包括:
- 视图和物化视图作为常规数据库表(
view
模块) - 常用数据库引擎的默认类型(
schema
模块) - 数据库连接/会话管理(
manager
模块)
安装
从PyPi安装(首选方法)
pip install lc-sqlalchemy-dbutils
使用Pip
从GitHub安装 ^{pr2}$其中x.x.x
是要下载的版本。在
手动下载安装
要下载源分发和/或控制盘文件,请导航到
https://github.com/libcommon/sqlalchemy-dbutils-py/tree/releases/vx.x.x/dist
,其中x.x.x
是要安装的版本,
并通过用户界面或wget等工具进行下载。然后安装运行:
pip install <downloaded file>
下载后请不要更改文件名,因为Pip需要安装文件的特定命名约定。在
依赖关系
sqlalchemy-dbutils-py
依赖于SQLAlchemy,并设计为与SQLAlchemy一起工作。只有Python
正式支持>;=3.6版本。在
入门
视图
view
模块公开了一个函数create_view
,用于创建类似ORM表的(具体化)视图。在
fromsqlalchemyimportColumn,Integer,Textfromsqlalchemy.ext.declarativeimportdeclarative_basefromsqlalchemy.sqlimportselectfromlc_sqlalchemy_dbutils.viewimportcreate_viewBaseTable=declarative_base()classUser(BaseTable):id=Column(Integer,primary_key=True)name=Column(Text,nullable=False)email_address=Column(Text,nullable=False)# Creates view named "vuser_names" as "SELECT id, name FROM user"UserNames=create_view("vuser_names",select([User.id,User.name]),BaseTable.metadata)
指向数据库中的UserNames
视图的UserNames
类型可以像任何其他ORM表类一样使用。
对于Postgres数据库,可以将materialized
参数设置为True
,以生成MATERIALIZED VIEW
。为
有关与标准SQL视图的区别的详细信息,请参见https://www.postgresql.org/docs/current/rules-materializedviews.html。在
数据库类型
schema
模块定义了一个类型来为默认的日期时间/时间戳值生成数据库表达式。
一种常见的数据库设计模式是使用datetime/timestamp列来跟踪何时创建和/或修改记录。
TimestampDefaultExpression
类型可以与server_default
参数一起使用
Column constructor。在
fromsqlalchemyimportColumn,Integer,Text,TIMESTAMPfromsqlalchemy.ext.declarativeimportdeclarative_basefromsqlalchemy.sqlimportselectfromlc_sqlalchemy_dbutils.schemaimportTimestampDefaultExpressionBaseTable=declarative_base()classUser(BaseTable):id=Column(Integer,primary_key=True)name=Column(Text,nullable=False)email_address=Column(Text,nullable=False)created_at=Column(TIMESTAMP(True),nullable=False,server_default=TimestampDefaultExpression())
注意使用TIMESTAMP(True)
,因为TimestampDefaultExpression
类型将尝试生成一个表达式来
在所有情况下检索UTC时间戳。在
数据库连接管理
manager
模块公开了一个类DBManager
,用于使用更高级别的方法管理数据库连接和会话。
只需使用RFC-1738兼容的连接URL创建一个DBManager
的实例,通过该实例,您可以
连接到数据库服务器,生成ORMSessions,
使用ORM对象构建查询,在活动会话中添加和删除记录,以及提交或回滚事务。在
importsysfromsqlalchemyimportColumn,Integer,Textfromsqlalchemy.ext.declarativeimportdeclarative_basefromsqlalchemy.sqlimportselectfromlc_sqlalchemy_dbutils.managerimportDBManagerBaseTable=declarative_base()classUser(BaseTable):id=Column(Integer,primary_key=True)name=Column(Text,nullable=False)email_address=Column(Text,nullable=False)defmain()->int:# Get commandline argumentsconfig_path_str=sys.argv[1]name_filter=sys.argv[2]# Create DB manager from connection URL in config file# and attach MetaData object from BaseTablemanager=(DBManager.from_file(config_path_str).with_metadata(BaseTable.metadata))# Connect to database (but don't generate a session yet)manager.connect()# NOTE: connect() is effectively equivalent to# manager.create_engine().create_session_factory(), but it can also# call the bootstrap_db() method to create all tables in the database.# The caveat with using connect() is that you cannot pass specific kwargs# to create_engine() or create_session_factory().# Create an active database Sessionmanager.gen_session()# Query the "user" table for the name specified on the commandlinematching_user=manager.query(User,name=name_filter).first()ifmatching_user:print("Found matching user with name {} (ID: {})",name_filter,matching_user.id)else:print("Did not find matching user with name {}",name_filter)# Close active session and dispose of database engine (which closes all connections)# NOTE: close_engine() automatically calls close_session()manager.close_engine()return0if__name__=="__main__":main()
上面的脚本将从提供的配置文件路径读取数据库连接URL,连接到数据库
并生成一个Session
,运行一个查询来找到第一个User
记录,其中name
与提供的名称过滤器匹配,
然后打印结果。这只是一个(大量注释)的示例,说明了使用DBManager
可以轻松地进行会话管理
班级。在
贡献/建议
欢迎投稿和建议!要提出功能请求,请报告错误,或对现有的 功能,请提交问题。如需投稿,请提交一份个人简历,但请务必进行打印、类型检查和测试 你的代码。提前谢谢!在
- 项目
标签: