-1

I created a Flask app with SQLAlchemy. I initialised the database in app.py but I want to use it in another file: otherfile.py.

app.py

app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_database'
db = SQLAlchemy(app)
print("TEST")

otherfile.py

from app import db
print(db)

But I get the error.

ImportError: cannot import name 'db'

Basically, I am doing this because I do not want to write the SQLAlchemy logic in app.py but I want to keep it in another file.

In addition, I just want the variable db to be exported. I do not want that when I run otherfile.py, this runs also print("TEST") which is in app.py

I looked at these answer with little luck:

How to share the global app object in flask?

Split Python Flask app into multiple files

How to divide flask app into multiple py files?

1 Answer 1

2

The SQLAlchemy class doesn't need to receive the app param on its initialization. So what you can do is create the db object in your otherfile.py and import it in app.py, where you can pass it the app object with SQLAlchemy.init_app().

app.py

from flask import Flask
from otherfile import db

app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_database'

db.init_app(app)

otherfile.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! How can I now connect in otherfile.py my sqlite database? Or is it already connected since I wrote in app.py app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_database)?
@Prova12 It will connect once that it is needed using the credentials that you set in app.config

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.