1

I am following the Flask SQLalchemy Quickstart which has all of the code in a single file:

Here is my initial index.py:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

# [snip] - some classes related to SQLAlchemy are here 

if __name__ == '__main__':
    app.run(host='0.0.0.0')

I want to split the code up a bit, so I created a separate file called database.py which will contain all of the database related code, and be imported as a module.

I modified my index.py to look like this:

from flask import Flask

# Import my database module
import database

app = Flask(__name__)

if __name__ == '__main__':
    app.run(host='0.0.0.0')

And the file database.py:

from flask.ext.sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI]'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

# [snip] - some classes related to SQLAlchemy are here 

Obviously when I try to run this code I get the following error:

File "database.py", line 5, in <module>
    app.config['SQLALCHEMY_DATABASE_URI]'] = 'sqlite:////tmp/test.db'
NameError: name 'app' is not defined

I can see that this is because the app object only exists within the parent module.

I could put the following lines back into index.py:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

But this creates a similar problem, whereby db is not available within the database.py file.

What is the correct way to code this?

2 Answers 2

1

You can import the object app into database.py by putting:

from index import app

in database.py.

Sign up to request clarification or add additional context in comments.

Comments

0

Edited answer after comment:

Simply use

from index import app

in database.py.

Alternatively, with the

import index

statement, use index.app instead of app only.

This should help you get out of python's import hell.

Btw: Not sure which IDE you are using. I like pycharm a lot. Using it you can refactor code and issues such as above are prevented automagically.

1 Comment

I think you got the relationship the wrong way around: index defines app, database needs it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.