-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?

davidism
  • 121,510
  • 29
  • 395
  • 339
Prova12
  • 643
  • 1
  • 7
  • 25

1 Answers1

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()
davidism
  • 121,510
  • 29
  • 395
  • 339
miguescri
  • 71
  • 3
  • 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 Jan 13 '20 at 14:39
  • 1
    @Prova12 It will connect once that it is needed using the credentials that you set in app.config – miguescri Jan 13 '20 at 15:32