0

I have recently started learning flask and SQLAlchemy. Upon creating a basic print hello application, I am getting the following error:

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.

File name: flask-hello-app.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:yolo0807@localhost:5432/example'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Person(db.Model):
    __tablename_ = 'persons'
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(),nullable = False)


db.create_all()
@app.route('/')

def index():
    return 'Hello world!'  

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=3000)```

---------------------------------------------------------------------
"""
Using suggested solutions to a similar problem: https://stackoverflow.com/questions/31444036/runtimeerror-working-outside-of-application-context

I replaced 

       db.create_all()

with

def test_connection(self):
    with app.app_context():
        db.create_all()


This eliminates the error and allows me to run the application but however upon running the following commands on my terminal:

psql example
\dt


The table persons does not show up and is not created.

(Please keep in mind that this is my first stack overflow question and I might've lacked efficiency in explaining my problem but I would try to be as active possible here and respond to any queries that might help you help me better.)
"""

0 Answers0