Dividing such a small application into modules is difficult, because you will find many cases where the two modules you create must mutually import each other, creating circular dependencies.
I recommend that you look at how to properly structure a larger application using the app factory function and delayed initialization of all extensions. An example application that does this, Flasky , is shown in my book.
All that is said, you can divide the application into two parts, you just need to be careful where you place the import statements. In the example below, I decided to move the instance creation of db and User to the models.py file.
Here is the main application module:
from flask import Flask from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' from models import db
And here is models.py:
from __main__ import app from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128))
Here, the main module will create the app , and only then import models.py. When models.py tries to import the app from the main module, it is already created. If you move from models import db to the top of the file, others import this code.
source share