Minimalist python orm framework(python orm/utils)
来源:SegmentFault
时间:2023-02-16 15:29:12 358浏览 收藏
你在学习数据库相关的知识吗?本文《Minimalist python orm framework(python orm/utils)》,主要介绍的内容就涉及到MySQL、ORM、python,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
Python ORM and Utils
python下的极简orm框架,核心思想,领域对象+仓库
地址:https://github.com/Dreampie/p...
1、特色
1、自动化的模型结构映射,不需要复杂的创建数据模型和数据库表结构直接的映射信息,只需要一个简单的继承就可以实现属性自动映射
class Example(MysqlBaseModel):
def __init__(self):
super(Example, self).__init__(table_name='example')
#使用
example= Example()
...
example.save() #对象的增删改查 轻松实现
2、超轻量级的配置初始化,只需要在 config.ini 配置对应的数据库信息,自动初始化连接,随时随地的执行sql
3、简单实用的日志工具
# 配置 config.ini
log.path = /opt/logs/pesto-orm/pesto-orm.log
log.level = INFO
# 使用简单
logger = LoggerFactory.get_logger('dialect.mysql.domain')
4、支持数据库事务
#一个注解告别,python下的事务烦恼
@transaction()
def methodX():
pass
5、环境隔离的参数配置工具 config.ini, 公共参数放default,定制参数放在各自的环境
[default] [dev] [test] [prod]
6、等等
2、结构
领域对象:领域模型对应的属性和行为
仓库:批量操作领域对象,或者特殊的一些数据操作逻辑
领域服务:统筹领域模型的行为,或者更复杂的单个模型无法完成的行为
只需要配置数据库相关的参数,通过领域模型,或者仓库即可操作数据,简单易用,业务逻辑复杂可以加入领域服务概念
3、示例
pesto-example(flask + pesto-orm)
build in python 3.6
add dependencies in requirements(重要):
pesto-orm==0.0.1 mysql-connector-python==8.0.11 Flask==1.0.2
add config in config.ini(重要):
[DEFAULT] app.key = pesto-orm log.path = /opt/logs/pesto-orm/pesto-orm.log log.level = INFO ; db config 目前只支持mysql,欢迎提交其他数据库的实现 db.database = example db.raise_on_warnings = True db.charset = utf8mb4 db.show_sql = True ; profiles config for env [local] db.user = root db.password = db.host = 127.0.0.1 db.port = 3306 [dev] [test] [prod]
run with env(default is local, dev, test, prod)
env=$ENV python ./pesto_example/main.py >> std_out.log 2>&1
main 示例example,可以直接执行main方法启动(需先执行数据库的创建,以及配置数据的相关信息)
@app.route('/')
def index():
data = {'name': 'pesto-example'}
return jsonify(data)
if __name__ == '__main__':
port = 8080
try:
app.run(host='0.0.0.0', port=port)
except (KeyboardInterrupt, SystemExit):
print('')
logger.info('Program exited.')
except (Exception,):
logger.error('Program exited. error info:\n')
logger.error(traceback.format_exc())
sys.exit(0)
model 模型创建,只需要配置对应的表名和主键,领域模型的行为可以扩展到该类
class Example(MysqlBaseModel):
def __init__(self):
super(Example, self).__init__(table_name='example', primary_key='id')
repository 依赖于模型,执行批量或者复杂的sql逻辑
class ExampleRepository(MysqlBaseRepository):
def __init__(self):
super(ExampleRepository, self).__init__(Example)
router api的路由信息,数据操作方式
app_example = Blueprint('example', __name__, url_prefix='/examples')
example_repository = ExampleRepository()
@app_example.route('', methods=['GET'])
def examples():
# 条件查询
data = example_repository.query_by(where="")
if len(data) ', methods=['GET'])
def example(id):
# 条件查询
data = example_repository.query_first_by(where="`id`= %s", params=(id,))
if data is None:
jsonify(error="not found any data"), 404
return jsonify(data)
@app_example.route('', methods=['POST'])
def save():
data = request.get_json()
if data is not None and len(data) > 0:
example = Example()
example.set_attrs(data)
example.created_at = datetime.datetime.now()
example.updated_at = datetime.datetime.now()
# 保存数据
example.save()
return jsonify(example.id)
else:
return jsonify(error="not found any data to save"), 400
@app_example.route('/<id>', methods=['DELETE'])
def delete(id):
result = True
example = Example()
example.id = id
example.deleted_at = datetime.datetime.now()
# 根据id删除数据
example.delete()
return jsonify(result)
@app_example.route('/<id>', methods=['PUT'])
def update(id):
result = True
data = request.get_json()
example = Example()
example.set_attrs(data)
example.id = id
example.updated_at = datetime.datetime.now()
# 根据id更新数据
example.update()
return jsonify(result)
</id></id>
创建数据库
create database example;
create table example(
id INT UNSIGNED AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
deleted_at DATETIME NOT NULL,
PRIMARY KEY(id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
4、测试
# 查询全部数据
curl -X GET \
http://localhost:8080/examples
# 添加一条数据
curl -X POST \
http://localhost:8080/examples \
-H 'content-type: application/json' \
-d '{
"title":"第三个测试"
}'
# 根据id查询
curl -X GET \
http://localhost:8080/examples/1
# 根据id 更新数据
curl -X PUT \
http://localhost:8080/examples/1 \
-H 'content-type: application/json' \
-d '{
"title":"这是第一个已改测试"
}'
# 根据id删除数据
curl -X DELETE \
http://localhost:8080/examples/3
以上就是《Minimalist python orm framework(python orm/utils)》的详细内容,更多关于mysql的资料请关注golang学习网公众号!
-
499 收藏
-
244 收藏
-
235 收藏
-
157 收藏
-
101 收藏
-
117 收藏
-
411 收藏
-
420 收藏
-
264 收藏
-
266 收藏
-
392 收藏
-
333 收藏
-
234 收藏
-
448 收藏
-
416 收藏
-
225 收藏
-
145 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习