2 kickfick123 kickfick123 于 2018.02.15 00:07 提问

Flask blueprint: cannot import name 'main' 20C

用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个回答

caozhy
caozhy   Ds   Rxr 2018.02.15 10:41

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

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!