前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >flask中使用SQLAlchemy操作mysql的一些注意事项和坑

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

作者头像
Python之道
发布2020-08-18 18:32:48
1.2K0
发布2020-08-18 18:32:48
举报
文章被收录于专栏:程序员八阿哥程序员八阿哥

一 ImportError: cannot import name 'db'

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

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

image
image

二 The sqlalchemy extension was not registered to the current application

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

image
image

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

image
image

三 No module named 'MySQLdb' flask

安装pymysql : pip install pymysql

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

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost: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中直接返回对象即可:

image
image

页面测试:

image
image

ok!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一 ImportError: cannot import name 'db'
  • 二 The sqlalchemy extension was not registered to the current application
  • 三 No module named 'MySQLdb' flask
  • 四 flask 'User' object is not iterable
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档