Skip to content

Instantly share code, notes, and snippets.

@dAnjou
Created July 22, 2012 20:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dAnjou/3161012 to your computer and use it in GitHub Desktop.
Save dAnjou/3161012 to your computer and use it in GitHub Desktop.
Flask: circular import problem
Traceback (most recent call last):
File "server.py", line 8, in <module>
from models import User
File "/home/max/Projekte/flask-testing-stuff/models.py", line 1, in <module>
from server import db
File "/home/max/Projekte/flask-testing-stuff/server.py", line 8, in <module>
from models import User
ImportError: cannot import name User
from server import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
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)
from models import User
#class User(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# username = db.Column(db.String(80), unique=True)
@app.route('/<name>')
def index(name):
user = User()
user.username = name
db.session.add(user)
db.session.commit()
return str(User.query.all())
if __name__ == '__main__':
from os.path import isfile
if not isfile('/tmp/test.db'):
db.create_all()
app.run(debug=True)
14:35:00 < mitsuhiko> dAnjou: setup i would recommend:
14:35:09 < mitsuhiko> __init__.py makes the flask extension instances
14:35:14 < mitsuhiko> views.py has the view functions in a blueprint
14:35:23 < mitsuhiko> models.py has your models
14:35:35 < mitsuhiko> app.py has a function that imports everything and makes an instance of the app in a function
14:35:57 < mitsuhiko> nothing depends on app.py but views can import models just fine
14:36:01 < mitsuhiko> and all of them can import from __init__.py
14:36:08 < mitsuhiko> because it has no dependency on anything else
@zjyExcelsior
Copy link

It's ugly in solution_could_be file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment