首页 > 其他分享 >RuntimeError Working outside of application context 解决方案

RuntimeError Working outside of application context 解决方案

时间:2023-06-05 18:36:30浏览次数:32  
标签:__ Working Column RuntimeError db application context 100 app

RuntimeError Working outside of application context 解决方案

前言

最近做了一个前后端分离的博客网站项目,后端采用了python轻量级框架Flask,在调用Flask sqlalchemy 的时候出现了问题。

报错

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///articles.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 数据库
db = SQLAlchemy(app)
# 数据模型
class Article(db.Model):
    __tablename__ = "article_table"
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    info = db.Column(db.String(100))
    datahtml = db.Column(db.Text(65536))
    time = db.Column(db.Date())

class User(db.Model):
    __tablename__ = "user_table"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100))
    password = db.Column(db.String(100))
    token = db.Column(db.String(100))
    token_time = db.Column(db.String(100))

//运行到这里就报错
db.create_all()

报错信息为:

line 47, in <module>
    db.create_all()
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.

在查看报错信息后发现是缺少上下文,需要在with app.app_context()下运行。
解决方案:

with app.app_context():
	db.create_all()

总结

在查阅Flask sqlalchemy官方文档后,才知道新版本需要特别声明上下文。

标签:__,Working,Column,RuntimeError,db,application,context,100,app
From: https://www.cnblogs.com/henda233/p/17458664.html

相关文章