Flask使用SQLAlchemy,db.create_all()报错

博客主要讲述了Flask项目使用SQLAlchemy时,db.create_all()报错的问题。给出代码示例后,介绍了两种解决方法,一是进入项目文件夹后输入flask shell再执行命令,二是输入python3.9后执行命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Flask项目使用SQLAlchemy,db.create_all()报错

代码如下:

app.py

from flask import Flask, render_template
# import SQLALchemy
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
with app.app_context():
    # set the SQLALCHEMY_DATABASE_URI key
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///song_library.db'
    app.config['SECRET_KEY'] = 'you-will-never-guess'
    # create an SQLAlchemy object named `db` and bind it to your app
    db = SQLAlchemy(app)

# a simple initial greeting
@app.route('/')
@app.route('/index')
def greeting():
    return render_template('greeting.html')


# app name
@app.errorhandler(404)
def not_found(e):
    return render_template("404.html")

models.py:

from app import app, db


# the User model: each user has a username, and a playlist_id foreign key referring
# to the user's Playlist
class User(db.Model):
    __table_args__ = {'extend_existing': True}
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), index=True, unique=True)
    playlist_id = db.Column(db.Integer, db.ForeignKey('playlist.id'))

    # representation method
    def __repr__(self):
        return "{}".format(self.username)

接下来我cd进项目文件夹,输入python3,再执行下面三条命令时

>>> from app import db
>>>> from models import *
>>>> db.create_all()

前两条都能正常执行,最后一条命令会报如下错误:

>>> db.create_all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/luca/opt/anaconda3/lib/python3.9/site-packages/flask_sqlalchemy/extension.py", line 868, in create_all
    self._call_for_binds(bind_key, "create_all")
  File "/Users/luca/opt/anaconda3/lib/python3.9/site-packages/flask_sqlalchemy/extension.py", line 839, in _call_for_binds
    engine = self.engines[key]
  File "/Users/luca/opt/anaconda3/lib/python3.9/site-packages/flask_sqlalchemy/extension.py", line 628, in engines
    app = current_app._get_current_object()  # type: ignore[attr-defined]
  File "/Users/luca/opt/anaconda3/lib/python3.9/site-packages/werkzeug/local.py", line 513, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

解决方法1:

cd进项目文件夹之后不要输入python3,而是输入flask shell,再执行上面的三条命令

解法方法2:

cd进项目文件夹之后不要输入python3,而是输入python3.9,再执行上面的三条命令

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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LucaTech

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值