Flask Back-end and Postgres Database connecting issue

63 views Asked by At

I'm working on a project that uses a Flask back-end and postgres database. I'm in the process of connecting my database, creating the tables and models but I'm having trouble when I go to db.create_all(). I'm getting this error after I try to db.create_all() in the python shell -

Traceback (most recent call last): File "", line 1, in File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 900, in create_all self._call_for_binds(bind_key, "create_all") File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 871, in _call_for_binds engine = self.engines[key] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 687, in engines app = current_app._get_current_object() # type: ignore[attr-defined] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/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.

db.create_all() Traceback (most recent call last): File "", line 1, in File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 900, in create_all self._call_for_binds(bind_key, "create_all") File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 871, in _call_for_binds engine = self.engines[key] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 687, in engines app = current_app._get_current_object() # type: ignore[attr-defined] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/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.

db.create_all() Traceback (most recent call last): File "", line 1, in File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 900, in create_all self._call_for_binds(bind_key, "create_all") File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 871, in _call_for_binds engine = self.engines[key] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 687, in engines app = current_app._get_current_object() # type: ignore[attr-defined] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/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.

db.create_all() Traceback (most recent call last): File "", line 1, in File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 900, in create_all self._call_for_binds(bind_key, "create_all") File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 871, in _call_for_binds engine = self.engines[key] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/site-packages/flask_sqlalchemy/extension.py", line 687, in engines app = current_app._get_current_object() # type: ignore[attr-defined] File "/Users/tasniabhuiyan/Documents/olfacto/server/.venv/lib/python3.10/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.

However I do have an app.app_context in my initialize_db.py -

from app import create_app, db

app = create_app()

def initialize_database():
    print("Initializing database...")
    app = create_app()
    with app.app_context():
        print("Inside application context.")
        db.create_all()
        print("Database tables created successfully.")

if __name__ == "__main__":
    initialize_database()

Here is also my run.py -

from app import create_app
from dotenv import load_dotenv
from app.initialize_db import initialize_database
import os

load_dotenv()

app = create_app()

initialize_database()

print("DATABASE_URL in app initialization:", os.getenv("DATABASE_URL"))
print(os.getenv("DEV_DATABASE_URL"))

@app.route('/print_db_url')
def print_db_url():
    db_url = app.config['SQLALCHEMY_DATABASE_URI']
    print("DATABASE_URL in route:", db_url)
    return f"The value of DATABASE_URL is: {db_url}"

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

and my init.py -

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
import os

load_dotenv()

db = SQLAlchemy()

def create_app(environment='development'):
    app = Flask(__name__)
    
    if environment == 'development':
        app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("DEV_DATABASE_URL")
    else:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv("DATABASE_URL")
        
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    print("Loaded configuration:")
    print(app.config)

    print("SQLALCHEMY_DATABASE_URI:", app.config['SQLALCHEMY_DATABASE_URI'])
    
    db.init_app(app)
    
    
    return app

also this is my directory if that helps as well -

 server
│
├── app/
│   ├── __init__.py
│   ├── initialize_db.py
│   ├── models.py
│   ├── routes.py
│   └── ...
│
├── run.py
├── config.py
├── requirements.txt
└── ...
0

There are 0 answers