darlingmz
向前看,向前迈!

学习地址

https://www.runoob.com/python3/python3-mysql.html(菜鸟教程)

选用:PyMySQL

PyMySQL 采用纯 Python 开发,兼容 MySQLdb,性能不如 MySQLdb,安装方便,支持 Python3。

实现

1.python中实现创建数据库

一般路径:models/servicesuser.py
核心语句:db.Column(db.String(100))

```python
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()
检查:运行脚本后,检查数据库表是否创建表成功

```python
"""
创建数据库及初始化
"""
if __name__ == '__main__':
db.create_all()
```

3.支持插入/查询数据库函数


一般路径:models/dao/servicesuser.py
功能:增加、查询
```python
@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

```python
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
```python
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)
```

实际运用如下:

__init__.py
```python
from threading import Lock
from application import db

lock = Lock()
db_lock = Lock()

def lock_mysql(func):
# 数据库操作加锁
def inner(*args, **kwargs):
with db_lock:
res = func(*args, **kwargs)
db.session.commit()
db.session.close()
return res
return inner
```

设置成装饰器给方法额外调用

```python
@lock_mysql
def is_task_created(task_id):
t1 = time.time()
while True and time.time() - t1 < 60:
info = Task.query.filter_by(task_id=task_id).one()
if info:
return True
time.sleep(2)
return False
```

posted on 2022-02-21 22:36  darlingmz  阅读(358)  评论(0编辑  收藏  举报