0

I got this error running the application with this command 'python manage.py runserver'

the error

C:\Users\Kamran\Envs\thermos\lib\site-packages\flask_sqlalchemy\__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warning.
  warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warning.')
Traceback (most recent call last):
  File "manage.py", line 1, in <module>
    from thermos import app, db
  File "E:\Kamran\My Work\Website\Python Flask Tutorial\thermos\thermos\__init__.py", line 13, in <module>
    import models
  File "E:\Kamran\My Work\Website\Python Flask Tutorial\thermos\thermos\models.py", line 3, in <module>
    from thermos import db
ImportError: cannot import name db

and I have managed my files like this

enter image description here enter image description here


manage.py

from thermos import app, db
from thermos.models import User
from flask.ext.script import Manager, prompt_bool

manager = Manager(app)

@manager.command
def initdb():
    db.create_all()
    db.session.add(User(username='Cameron', email='cameron@google.com'))
    db.session.add(User(username='Mahshid', email='mahshid@python.org'))
    db.session.commit()
    print 'Initialized the database'

@manager.command
def dropdb():
    if prompt_bool(
    'Are you sure you want to lose all your data'):
        db.drop_all()
        print 'Dropped the database'

if __name__ == '__main__':
    manager.run()

init.py

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'K\xa5r\x94\xc2"\x06\x14\'\xc1\xe4\xa6\r\x9f\x16\xf9z4hIR\x14g\x1c'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'thermos.db')
app.config['DEBUG'] = True
db = SQLAlchemy(app)

import models
import views

models.py

from datetime import datetime
from sqlalchemy import desc
from thermos import db

class Bookmark(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)
    description = db.Column(db.String(300))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    @staticmethod
    def newest(num):
        return Bookmark.query.order_by(desc(Bookmark.date)).limit(num)

    def __repr__(self):
        return '<Bookmark "{}": "{}">'.format(self.description, self.url)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    bookmarks = db.relationship('Bookmark', backref='user', lazy='dynamic')

    def __rep__(self):
        return '<User %r>' % self.username

views.py

from flask import render_template, redirect, url_for, flash
from thermos import app, db
from forms import BookmarkForm
from models import User, Bookmark

def logged_in_user():
    return models.User.query.filter_by(username='Cameron').first()

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html', new_bookmarks=models.Bookmark.newest(5))

@app.route('/add', methods = ['GET', 'POST'])
def add():
    form = BookmarkForm()
    if form.validate_on_submit():
        url = form.url.data
        description = form.description.data
        bm = models.Bookmark(user=logged_in_user(), url=url, description=description)
        db.session.add(bm)
        db.session.commit()
        flash('stored "{}"'.format(description))
        return redirect(url_for('index'))
    return render_template('add.html', form=form)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def page_not_found(e):
    return render_template('500.html'), 500 

if __name__=='__main__':
    app.run(debug=True)
zEn feeLo
  • 1,877
  • 4
  • 25
  • 45
  • So where is the thermos db? I can't see any class/library/file named db and you just import and use them. Did you delete by mistake or forgot to copy from somewhere? – Fma Aug 17 '16 at 06:31
  • Updated , in the second thermos folder – zEn feeLo Aug 17 '16 at 06:34
  • No the db working in the command line with no problem, I used the inner python DB SQLite – zEn feeLo Aug 17 '16 at 06:35
  • Are you using pip to install this? – applecrusher Aug 17 '16 at 06:37
  • yes pip install ... – zEn feeLo Aug 17 '16 at 06:38
  • I think you have a circular import. You import User and use the import db in the model as well. So I think that is causing this issue. Based on this question as well: http://stackoverflow.com/questions/31693683/python2-7flask-reference-to-import-variable-from-init-py-inside-module – applecrusher Aug 17 '16 at 06:43
  • Your import order is messed I guess can you check them? – Fma Aug 17 '16 at 06:45
  • I cant remove import db in the models? what should I do ? – zEn feeLo Aug 17 '16 at 06:47
  • @Fma I tried to organized my code and this problem happend, what should I do ? – zEn feeLo Aug 17 '16 at 06:50
  • First of all remove last two import lines from `__init__.py` it causes circular import as @applecrusher said. Your imports and some files need reorganizing. – Fma Aug 17 '16 at 06:57
  • @Fma I removed and I got 2 errors instead of 3, it says File "manage.py", line 2, in from thermos.models import User File "E:\Kamran\My Work\Website\Python Flask Tutorial\thermos\thermos\models.py", line 3, in from thermos import db ImportError: cannot import name db – zEn feeLo Aug 17 '16 at 07:00
  • Solving circular import is a headache.. Check this answer and try to understand how it works: http://stackoverflow.com/a/3956038 Basically you should not import classes and import modules instead. – Fma Aug 17 '16 at 07:07
  • Is there any other solution instead to prevent Circular import problem? I'm new to python and flask – zEn feeLo Aug 17 '16 at 07:16
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/121130/discussion-between-cameron-a-and-fma). – zEn feeLo Aug 17 '16 at 08:15

1 Answers1

1

It is not the Cirular Import problem, Its bad addressing the modules

In the views.py

from flask import render_template, redirect, url_for, flash
from thermos import models, app, db
from forms import BookmarkForm
from models import User, Bookmark
zEn feeLo
  • 1,877
  • 4
  • 25
  • 45
  • I in the views.py I wrote from thermos import models, app, db In the manage.py I first edited the question , I update it now – zEn feeLo Aug 17 '16 at 10:51
  • I wrote import models and import views in the end of my __init__ file just like the question, thanks for mentioning, I edited the answer – zEn feeLo Aug 17 '16 at 10:54