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

一 ImportError: cannot import name 'db'

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

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

 

二 The sqlalchemy extension was not registered to the current application

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

if __name__ == '__main__':里面注册:

 

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

 


 

三 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中直接返回对象即可:

页面测试:

ok!

 

转载于:https://www.cnblogs.com/houzheng/p/10980425.html

from flask import Flask, render_template, request, redirect, url_for, flash import pymysql from datetime import datetime app = Flask(__name__) # 配置数据库连接 app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '1' app.config['MYSQL_DB'] = 'message_board' app.config['MYSQL_CURSORCLASS'] = 'DictCursor' # 配置会话密钥 app.secret_key = 'your_secret_key' # 首页 - 分页显示留言 @app.route('/') @app.route('/page/<int:page>') def index(page=1): # 每页显示的留言数量 per_page = 5 # 计算偏移量 offset = (page - 1) * per_page # 连接数据库 conn = pymysql.connect( host=app.config['MYSQL_HOST'], user=app.config['MYSQL_USER'], password=app.config['MYSQL_PASSWORD'], database=app.config['MYSQL_DB'], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() # 获取总留言数 cur.execute("SELECT COUNT(*) as total FROM messages") total_data = cur.fetchone() total_messages = total_data['total'] # 计算总页数 total_pages = (total_messages + per_page - 1) // per_page # 获取当前页的留言 cur.execute("SELECT * FROM messages ORDER BY created_at DESC LIMIT %s OFFSET %s", (per_page, offset)) messages = cur.fetchall() return render_template('index.html', messages=messages, page=page, total_pages=total_pages) finally: # 关闭游标连接 cur.close() conn.close() # 添加留言 @app.route('/add', methods=['POST']) def add_message(): if request.method == 'POST': name = request.form['name'] content = request.form['content'] created_at = datetime.now() # 连接数据库 conn = pymysql.connect( host=app.config['MYSQL_HOST'], user=app.config['MYSQL_USER'], password=app.config['MYSQL_PASSWORD'], database=app.config['MYSQL_DB'], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("INSERT INTO messages (name, content, created_at) VALUES (%s, %s, %s)", (name, content, created_at)) conn.commit() flash('留言添加成功!') return redirect(url_for('index')) finally: # 关闭游标连接 cur.close() conn.close() # 修改留言 - 显示修改表单 @app.route('/edit/<int:id>') def edit_message(id): # 连接数据库 conn = pymysql.connect( host=app.config['MYSQL_HOST'], user=app.config['MYSQL_USER'], password=app.config['MYSQL_PASSWORD'], database=app.config['MYSQL_DB'], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("SELECT * FROM messages WHERE id = %s", (id,)) message = cur.fetchone() return render_template('edit.html', message=message) finally: # 关闭游标连接 cur.close() conn.close() # 修改留言 - 处理表单提交 @app.route('/update/<int:id>', methods=['POST']) def update_message(id): if request.method == 'POST': name = request.form['name'] content = request.form['content'] updated_at = datetime.now() # 连接数据库 conn = pymysql.connect( host=app.config['MYSQL_HOST'], user=app.config['MYSQL_USER'], password=app.config['MYSQL_PASSWORD'], database=app.config['MYSQL_DB'], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("UPDATE messages SET name = %s, content = %s, updated_at = %s WHERE id = %s", (name, content, updated_at, id)) conn.commit() flash('留言修改成功!') return redirect(url_for('index')) finally: # 关闭游标连接 cur.close() conn.close() # 删除留言 @app.route('/delete/<int:id>') def delete_message(id): # 连接数据库 conn = pymysql.connect( host=app.config['MYSQL_HOST'], user=app.config['MYSQL_USER'], password=app.config['MYSQL_PASSWORD'], database=app.config['MYSQL_DB'], cursorclass=pymysql.cursors.DictCursor ) try: # 创建游标 cur = conn.cursor() cur.execute("DELETE FROM messages WHERE id = %s", (id,)) conn.commit() flash('留言删除成功!') return redirect(url_for('index')) finally: # 关闭游标连接 cur.close() conn.close() if __name__ == '__main__': app.run(debug=True, use_reloader=False) 这个代码运行报错,帮我修改它
05-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值