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.