FlaskIntroduction
FlaskIntroduction copied to clipboard
RuntimeError: Working outside of application context. when creating SQLite DB
macOS Venture 13.4 Python 3.11.3
>>> from app import db
>>> db.create_all()
returns
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'db' is not defined
>>>
KeyboardInterrupt
>>> from app import db
>>> db.create_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/fthobe/dev/tagverified/env/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 884, in create_all
self._call_for_binds(bind_key, "create_all")
File "/Users/fthobe/dev/tagverified/env/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 855, in _call_for_binds
engine = self.engines[key]
^^^^^^^^^^^^
File "/Users/fthobe/dev/tagverified/env/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 636, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/fthobe/dev/tagverified/env/lib/python3.11/site-packages/werkzeug/local.py", line 508, 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.
when trying to create db from following code:
#Load the applications you need to run for your first webserver, render templates and link to static files
from flask import Flask, render_template, url_for
#Load the SQL Connector
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
#Create an app that hosts the service
app = Flask(__name__)
#Specify where the local SQLITE DB is located
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
#Specify what initialises the DB point to your app.py
db = SQLAlchemy(app)
#Start defining the DB and the columns
#Define a progressively numbered integer given by the DB for every item in the list
#A primary key is a column or group of columns used to identify the uniqueness of rows in a table. Each table has one and only one primary key.
#A db.string contains the task and can be maximum 200 characters long, nullable indicates that it can not be empty.
#Adds a boolean for every task created
#SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
#SQLite recognizes the keywords "TRUE" and "FALSE", as of version 3.23.0 (2018-04-02) but those keywords are really just alternative spellings for the integer literals 1 and 0 respectively.
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200), nullable=False)
completed = db.Column(db.Integer, default=0)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
with app.app_context():
db.create_all()
#"app.route" tell your server to which url it should respond. "/" means your base folder such as example.com/
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
#app.run starts the app and contains variables and configures the app to run on localhost ("host=0.0.0.0"), the port (you can use a different one than 80) and sets it in debug mode ("debug=True")
app.run(host='0.0.0.0', port=80, debug=True)
any idea?
@fthobe
you can add
if__name__ == '__main__':
#app.run starts the app and contains variables and configures the app to run on localhost ("host=0.0.0.0"), the port (you can use a different one than 80) and sets it in debug mode ("debug=True")
app.run(host='0.0.0.0', port=80, debug=True)
with app.app_context():
db.create_all()
Now try to run direct app.py file
Is your virtual environment active in the terminal you start the REPL in? The error hints that you're attempting to execute code outside of its working context which sounds like an environment issue to me
For those of you who faced the database creation error, do the following:
from app import app, db app.app_context().push() db.create_all()
it should be created under instance directory after those commands.
call manually in the flask shell , this is because I think in Flask-SQLAlchemy to access the DB db.engine and db.session requires an active Flask app context , when you run the CLI command a context will be pushed automatically.
flask shell,
db.create_all()
def create_tables(): db.create_all()
just add this lines after class Todo(db.Model) , after runing the app once put them as comment this worked for me