当前位置:网站首页>Flask操作多个数据库
Flask操作多个数据库
2022-04-23 05:47:00 【峰爷520】
config.py:
SQLALCHEMY_BINDS = {
"db1": "mysql+pymysql://db_user1:db_pwd1@db_host1:db_port1/db_name1?charset=utf8",
"db2": "mysql+pymysql://db_user2:db_pwd2@db_host2:db_port2/db_name2?charset=utf8",
}
models.py:
def dynamic_model(bind_key, model_n):
properties = {
"__tablename__" = model_n.__tablename__,
"__bind_key__" = bind_key
}
for col in dir(model_n):
if col.startswith('_'):
continue
properties[col] = getattr(model_n, col)
model = type(model_n.__tablename__, (db.Model,), properties)
return model
自定义序列化:
class Serialize:
def __init__(self, model):
self.query = model.query
self.model = model
self.columns = []
self.page_size = request.args.get('page_size', type=int, default=10)
self.current_page = request.args.get('page', default=1, type=int)
self.start = (self.current_page - 1) * self.page_size
self.end = self.start + self.page_size
self.field_func_map = {}
def field(self, *columns):
self.columns = columns
self.query = db.session.query(*[getattr(self.model, column) for column in columns])
return self
def search(self, **kw_map):
for column in kw_map:
if kw_map[column]:
self.query = self.query.filter(
getattr(self.model, column).like("%{}%".format('/' + kw_map[column]), escape='/'))
return self
def exclude(self, **kw_map):
for column in kw_map:
self.query = self.query.filter(
getattr(self.model, column) != kw_map[column])
return self
def custom_handle(self, **kargs):
self.field_func_map = kargs
return self
def to_json(self, **kw_map):
res = []
for column in kw_map:
self.query = self.query.filter(
getattr(self.model, column) == kw_map[column])
if self.columns:
for q in self.query.slice(self.start, self.end):
obj_dict = {}
for i, c in enumerate(self.columns):
if c in self.field_func_map:
obj_dict[c] = self.field_func_map[c.name](q[i])
else:
obj_dict[c] = q[i]
res.append(obj_dict)
else:
for q in self.query.slice(self.start, self.end):
obj_dict = {}
for c in class_mapper(q.__class__).columns:
if c.name in self.field_func_map:
obj_dict[c.name] = self.field_func_map[c.name](getattr(q, c.name))
else:
obj_dict[c.name] = getattr(q, c.name)
res.append(obj_dict)
return res
def total(self):
return self.query.count()
def data(self, **kw_map):
return {
'data': self.to_json(**kw_map),
'total': self.total(),
'currentPage': self.current_page,
'pageSize': self.page_size
}
版权声明
本文为[峰爷520]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_41752427/article/details/124327439
边栏推荐
- Understanding and installing MySQL
- 自动控制原理知识点整合归纳(韩敏版)
- Example of ticket selling with reentrant lock
- MySQL groups are sorted by a field, and the first value is taken
- @Problems caused by internal dead loop of postconstruct method
- 队列解决约瑟夫问题
- C language file operation
- Programming training
- Robocode教程8——AdvancedRobot
- [leetcode 350] intersection of two arrays II
猜你喜欢

基于pygame库编写的五子棋游戏

The most practical chrome plug-in

Explanation of the second I interval of 2020 Niuke summer multi school training camp

Integration and induction of knowledge points of automatic control principle (Han min version)

Import of data

基于Sentinel+Nacos 对Feign Client 动态添加默认熔断规则
![[leetcode 202] happy number](/img/b2/a4e65688aef3a0cec8088bcaba048f.jpg)
[leetcode 202] happy number

从源代码到可执行文件的过程

Rust的闭包类型(Fn, FnMut, FnOne的区别)

20 excellent plug-ins recommended by idea
随机推荐
Detection technology and principle
POI and easyexcel exercises
H. Are You Safe? Convex hull naked problem
用C语言实现重写strcmp等四个函数
Failure to deliver XID in Seata distributed transaction project
Excel打开超大csv格式数据
Easy to use data set and open source network comparison website
根据SQL语句查询出的结果集,将其封装为json
Type conversion in C #
Rust的闭包类型(Fn, FnMut, FnOne的区别)
Rust 中的 Rc智能指针
selenium+PhantomJS破解滑动验证2
7-21日错题涉及知识点。
Troubleshooting of data deleted and reappeared problems
安全授信
Guaba and Computational Geometry
10.Advance Next Round
Integration and induction of knowledge points of automatic control principle (Han min version)
Generation of verification code
Feign请求日志统一打印