1

Hi I'm trying to learn to build an app in flask using postgresql, but I can't get the database working properly. The tutorial I'm following has the following:

from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost/ip_calc'

db = SQLAlchemy(app)

class Event(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(100), nullable=False)
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    def __repr__(self):
        return f"Event: {self.description}"

    def __init__(self, description):
        self.description = description

@app.route('/')
def hello():
    return 'Hey!'

if __name__ == "__main__":
    app.run()

The tutorial then says to go to the terminal navigate to the correct folder and go into a python prompt and type the following:

from app import db
db.create_all()

but I just get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 884, in     create_all
    self._call_for_binds(bind_key, "create_all")
  File "/Users/robkinsey/.local/share/virtualenvs/backend-EjblJ9Ag/lib/python3.11/site-packages/flask_sqlalchemy/extension.py", line 855, in _call_for_binds
    engine = self.engines[key]
         ^^^^^^^^^^^^
  File "/Users/user/.local/share/virtualenvs/backend-EjblJ9Ag/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/user/.local/share/virtualenvs/backend-EjblJ9Ag/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.

How do I get the tables to create, I just expected it to work like it did in the tutorial it was only a year old.

iFunction
  • 1,208
  • 5
  • 21
  • 35
  • The last line in your error output is the informative one, you aren't running the dB setup in the correct context. There are multiple stack overflow questions on this already but you can find a particularly detailed answer here https://stackoverflow.com/questions/73999854/flask-error-runtimeerror-working-outside-of-application-context – Michael May 20 '23 at 15:38
  • Yes so it seems, but I'm really lost this was not in the tutorial, it just worked for him, so I dont' know how to get past this, I've been searching for hours. it seems I have a problem with psycopg2 as I can't import that on the command line now – iFunction May 20 '23 at 15:48
  • So I've just tried to create this all on the command line and get the same error. how do you get past it, I'm tryin to learn about this. This is supposed to be the just get you going tutorial, it can't be that difficult just to get a database table working in Flask, in Django it's very very simple, why is it not simple in Flask? – iFunction May 20 '23 at 15:56
  • The reason that it is harder in flask is that Django is a 'batteries included' framework (or close to it). Flask is more lightweight so you have to add all the parts you want manually which can be a bit harder. – Isaac Cooke May 20 '23 at 16:36
  • Ah, ok, that makes much more sense, so I'm guessing it is probably best to go right back to basics and just try to create a table using python and sqlalchemy first then the flask bit should be easier – iFunction May 20 '23 at 16:48

1 Answers1

1

You are trying to access the database with the wrong context (which the flask_sqlalchemy library requires). Try adding this to the end of your file.

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

Otherwise, run the with app.app_context(): (with the colon) in the shell before running the app.run() function.

  • I dont' get an error now, but it is not creating the database, would that be down to the connection string, and if so where would I find an error to be able to troubleshoot this please? – iFunction May 20 '23 at 16:00
  • Try this: `try: except Exception as err: print(f"Error: {err}")`. Remember to add indents and replace code with the `with app.app_context():` statement. – Isaac Cooke May 20 '23 at 16:33
  • Otherwise, you could create the database in PgAdmin of the command line and just connect to it. I'm not sure whether that would work though and you'd still need the connection string to connect to it. – Isaac Cooke May 20 '23 at 16:37