flask中使用SQLAlchemy操作mysql的一些注意事项和坑

一 ImportError: cannot import name 'db'

由于app最后才加载,所以其他文件,比如models.py不能从app.py导入任何变量,

要使用db可以先定义一个,之后再注册初始化即可:

flask中使用SQLAlchemy操作mysql的一些注意事项和坑
image

二 The sqlalchemy extension was not registered to the current application

没有注册导致的,网上很多方法都不对,应该在程序启动之前就注册,不能再

flask中使用SQLAlchemy操作mysql的一些注意事项和坑
image

只需要调用init_app即可,前提app要配置好数据库连接属性:

flask中使用SQLAlchemy操作mysql的一些注意事项和坑
image

三 No module named 'MySQLdb' flask

安装pymysql : pip install pymysql

然后修改app配置链接即可,加上pymysql:

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3307/test?charset=utf8"

四 flask 'User' object is not iterable

sqlalchemy model 定义的对象不能直接转dict,需要特殊转化一下

通过列表生成式获取所有属性,然后再通过反射获取所有属性和value转化为字典:
columns = [c.key for c in class_mapper(user.class).columns]
dict((c, getattr(user, c)) for c in columns)

实际中可以定义一个response类:

from flask import Response, jsonify
from sqlalchemy.orm import class_mapper

定义response返回类,自动解析json

class JSONResponse(Response):
@classmethod
def force_type(cls, response, environ=None):
if isinstance(response, dict): # 判断返回类型是否是字典(JSON)
response = jsonify(response) # 转换
if isinstance(response, db.Model): # 对象,只用db,Model即可转json
columns = [c.key for c in class_mapper(response.class).columns]
response = jsonify(dict((c, getattr(response, c)) for c in columns))
return super().force_type(response, environ)

view中直接返回对象即可:

flask中使用SQLAlchemy操作mysql的一些注意事项和坑
image

页面测试:

flask中使用SQLAlchemy操作mysql的一些注意事项和坑
image

ok!