db.Column(db.Integer, primary_key=True, autoincrement=True)
学习:
1.python中实现创建数据库
一般路径:models/servicesuser.py
核心语句:db.Column(db.String(100))
class 表名称(db.Model):
__tablename__ = "表名称"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user = db.Column(db.String(100))
environment = db.Column(db.String(100))
content = db.Column(db.String(100))
add_time = db.Column(db.DateTime, default=datetime.datetime.now,
onupdate=datetime.datetime.now)
__mapper_args__ = {
"order_by": add_time.desc()
}
2.python中实现创建数据表
一般路径:db_create.py
核心语言:db.create_all()
检查:运行脚本后,检查数据库表是否创建表成功
"""
创建数据库及初始化
"""
if __name__ == '__main__':
db.create_all()
3.支持插入/查询数据库函数
一般路径:models/dao/servicesuser.py
功能:增加、查询
@lock_mysql
def add_servicesuser_usergetinfo(**kw):
"""记录用户查询uid"""
add_usergetinfo= 表名称(**kw)
db.session.add(add_usergetinfo)
@lock_mysql
def get_servicesuser_userinfo_actions(page_index=0, page_size=10):
"""查询用户查询uid操作"""
q = 表名称.query
count = q.count()
# 为0时不分页
if page_index:
# error_out False: 当page_index超过最大页数时阻止抛出异常
result = q.paginate(page=page_index, per_page=page_size, error_out=False).items
else:
result = q.all()
return count, [Dict({
"id": info.id,
"user": info.user,
"environment": info.environment,
"content": info.content,
"add_time": str(info.add_time),
}) for info in result]
4.接口支持操作数据库函数
操作路径:application/servicesuser/views.py
核心:
ThreadPoolExecutor
submit
t = ThreadPoolExecutor(max_workers=3)
t.submit(add_servicesuser_usergetinfo,
**{
"user": data.get("user"),
"environment": data.get("environment"),
"content": f"uid={uid}"
})
t.shutdown(False)
5.请求接口获取数据库返回
application/servicesuser/views.py
class UserGetinfoActionsView(MethodView):
"""
获取用户查询uid的操作记录
"""
@staticmethod
# @app.base_action()
def post():
data = request.json
count, result = get_servicesuser_userinfo_actions(
data.get("page_index"),
data.get("page_size")
)
addgoldactions_dict = {
"code": 20000,
"data": result,
"total": count
}
return jsonify(addgoldactions_dict)