关于#Flask#的问题,如何解决?(语言-python)

Flask连接MySQL数据库时报错RuntimeError: Working outside of application context.
源码:

from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)

db = SQLAlchemy(app)

class Users(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key = True)
    username = db.Column(db.String(80),nullable = False)
    age = db.Column(db.Integer)
    email = db.Column(db.String(120),unique = True)

    def __init__(self,username,age,email):
         self.username = username
         self.age = age
         self.email = email
         with app.app_context():
             return
    def __repr__(self):
         return '' % self.username

db.create_all()
if __name__ == '__main__':
    app.run(debug=True)


只要在最后加上

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

就可以了

from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)

db = SQLAlchemy(app)

class Users(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key = True)
    username = db.Column(db.String(80),nullable = False)
    age = db.Column(db.Integer)
    email = db.Column(db.String(120),unique = True)

    def __init__(self,username,age,email):
         self.username = username
         self.age = age
         self.email = email
         with app.app_context():
             return
    def __repr__(self):
         return '<User:%r>' % self.username

db.create_all()
if __name__ == '__main__':
    app.run(debug=True)
    with app.app_context():
        db.create_all()

该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
这个错误通常是因为在没有应用上下文的情况下尝试访问Flask扩展或应用程序对象。您可以尝试将数据库连接代码移动到应用程序上下文中。

以下是一个示例:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@localhost/dbname'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Users(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer,primary_key = True)
    username = db.Column(db.String(80),nullable = False)
    age = db.Column(db.Integer)
    email = db.Column(db.String(120),unique = True)
 
    def __init__(self,username,age,email):
         self.username = username
         self.age = age
         self.email = email

    def __repr__(self):
         return '<User:%r>' % self.username

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

if __name__ == '__main__':
    app.run(debug=True)

在这个示例中,我们将数据库连接代码移动到了应用程序上下文中,这样就可以使用Flask扩展和应用程序对象了。此外,我们还将SQLAlchemy的跟踪修改设置为False,以避免在应用程序运行期间发出多余的警告信息。


如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

  • 建议你看下这篇博客👉 :python+Mysql+flask架构的在线留言板实战
  • 除此之外, 这篇博客: python+flask+mysql 用网页展示数据库内容中的 二、Flask.py 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • from flask import Flask,request
    from flask import render_template
    from mysql import Mysql
    
    app = Flask(__name__)
    
    @app.route('/index')
    def name():
        page = request.args.get('page')
        if not page or int(page) == 0:
            page = 1
        db = Mysql()
        keyword = request.args.get('keyword')
        items = db.getItems(page, keyword)
        page_range = range(int(page) - 3, int(page) + 2)
        if int(page) < 4:
            page_range = range(1, int(page) + 4)
        return render_template('index.html', items=items,page=int(page),prange = page_range)
    
    if __name__ == '__main__':
        app.run(app.run(debug=True,port=5222,host='127.0.0.1'))