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

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,再执行上面的三条命令

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LucaTech

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

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

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

打赏作者

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

抵扣说明:

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

余额充值