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)