导入错误瓶应用程序

时间:2016-08-17 06:25:33

标签: python flask import

使用此命令运行应用程序时出现此错误 'python manage.py runserver'

错误

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

我已经像这样管理了我的文件

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()

初始化的.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)

1 个答案:

答案 0 :(得分:1)

这不是Cirular Import问题,它对模块的解决不好

在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