kickfick123 2018-02-14 16:07 采纳率: 100%
浏览 2343
已采纳

Flask blueprint: cannot import name 'main'

用Flask写了一个web服务器,在用Blue print时,提示 cannot import name'main'。
把blue print两行注释掉正常运行。百度了一下,有可能是import的顺序有错误 https://segmentfault.com/a/1190000010600365
但不确定是不是这个问题,如果是该怎么调整?

Traceback提示:

 Traceback (most recent call last):
  File "C:/Personal/Peoplefinder/app.py", line 21, in <module>
    from Routes import main
  File "C:\Personal\Peoplefinder\Routes.py", line 11, in <module>
    from Models import User
  File "C:\Personal\Peoplefinder\Models.py", line 4, in <module>
    from app import lm
  File "C:\Personal\Peoplefinder\app.py", line 21, in <module>
    from Routes import main
ImportError: cannot import name 'main'

源码: app.py , Models.py , Routes.py

app.py

 from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)

path = os.path.dirname(__file__)
path = path + '\data\data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(path)
app.config['SECRET_KEY'] = 'kdije29fuk_ksdusii2w'

db = SQLAlchemy(app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
lm.session_protection = 'strong'

from Routes import main
app.register_blueprint(main)

if __name__ == '__main__':
    config = dict(
        debug=True,
        host='0.0.0.0',
        port=2000,
    )
    app.run(**config)

Models.py

 from flask_login import UserMixin, login_manager
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from app import lm

db = SQLAlchemy()


class User(db.Model, UserMixin):
    __tablename__ = "users"
    id = db.Column('user_id1', db.Integer, primary_key=True)
    username = db.Column('username', db.String(20), unique=True , index=True)
    password_hash = db.Column('password_hash', db.String(1000))

    def __init__(self, username, password):
        self.username = username
        self.password = password

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute/ password 不是一个可读属性。')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password, method='pbkdf2:sha256', salt_length=8)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    @property
    def is_authenticated(self):
            return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

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


@lm.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


Routes.py

 from flask import (
    render_template,
    request,
    redirect,
    flash,
    url_for,
    session,
    Blueprint

)
from Models import User
from flask_login import login_user


from app import db

main = Blueprint('main', __name__)

@main.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    user = User(request.form['username'], request.form['password'])
    db.session.add(user)
    db.session.commit()
    flash('User successfully registered')
    return redirect(url_for('login'))


@main.route('/login', methods=['GET', 'POST'])
def login():

    if request.method == 'GET':
        return render_template('login.html')
    username = request.form['username']
    password = request.form['password']
    u = User.query.filter_by(username=username).first()
    v = u.verify_password(password)
    if u is not None and v is True:
        login_user(u)
        print(session)
        print('成功')
        return redirect(url_for('index'))

    else:
        flash('Username or Password is invalid', 'error')
        print('失败')
        return redirect(url_for('register'))



@main.route('/', methods=['GET'])
def index():
    if request.method == 'GET':
        return render_template('index.html')


  • 写回答

1条回答 默认 最新

  • threenewbee 2018-02-15 02:41
    关注

    Routes中有错误,导致main无法加载,你可以参照官网的blueprintexample

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 10月1日

悬赏问题

  • ¥15 单纯型python实现编译报错
  • ¥15 c++2013读写oracle
  • ¥15 c++ gmssl sm2验签demo
  • ¥15 关于模的完全剩余系(关键词-数学方法)
  • ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题