RuntimeError: Working outside of application context

Share

Error – RuntimeError: Working outside of application context. in flask app when adding this line “db.create_all()”

The error occurs because you are trying to create the database tables outside of a Flask application context. To resolve this, you can create the database tables within the if __name__ == "__main__" block, after the application has been created and has been added to the context.

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///features.db'
db = SQLAlchemy(app)

class Feature(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    image_url = db.Column(db.String(200), nullable=False)
    feature_page_url = db.Column(db.String(200), nullable=False)
    title = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text, nullable=False)

@app.route("/")
def home():
    features = Feature.query.all()
    return render_template("home.html", features=features)

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

Share
Related  How to Change Password of MySQL || How to reset MySQL Password

Leave a Reply

Your email address will not be published. Required fields are marked *

Top 5 Most Expensive Domains Ever Sold 4 Must-Try ChatGPT Alternatives: Perplexity AI, BardAI, Pi, and More! Types of Trading Techniques in the Stock Market. ChatGPT app now available in India this AI chatbot can help you make your life more productive. What is wrong with following function code?