用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')