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