【问题标题】:Import error flask application导入错误烧瓶应用程序
【发布时间】:2016-12-23 16:30:23
【问题描述】:

使用此命令运行应用程序时出现此错误 '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

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


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)

【问题讨论】:

  • 那么热水瓶数据库在哪里?我看不到任何名为 db 的类/库/文件,您只需导入并使用它们。你是误删了还是忘了从某个地方复制?
  • 已更新,在第二个热水瓶文件夹中
  • 没有db在命令行中工作没有问题,我使用了内部python DB SQLite
  • 你是用pip安装的吗?
  • 是的 pip install ...

标签: python flask import


【解决方案1】:

这不是循环导入问题,而是对模块的错误寻址

在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

【讨论】:

  • 我在views.py中我从thermos导入models,app,db在manage.py中我首先编辑了问题,我现在更新它
  • 我在 init 文件的末尾写了导入模型和导入视图,就像问题一样,谢谢提及,我编辑了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
相关资源
最近更新 更多