尝试使用Python和Flask设置登录页面并获取错误:
(第33行是@login_required
)
Traceback (most recent call last):
File "routes.py", line 33, in <module>
@login_required
File "/home/pi/FlaskTutorial/local/lib/python2.7/site-packages/flask/app.py", line 1013, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/home/pi/FlaskTutorial/local/lib/python2.7/site-packages/flask/app.py", line 62, in wrapper_func
return f(self, *args, **kwargs)
File "/home/pi/FlaskTutorial/local/lib/python2.7/site-packages/flask/app.py", line 942, in add_url_rule
endpoint = _endpoint_from_view_func(view_func)
File "/home/pi/FlaskTutorial/local/lib/python2.7/site-packages/flask/helpers.py", line 60, in _endpoint_from_view_func
assert view_func is not None, 'expected view func if endpoint ' \
AssertionError: expected view func if endpoint is not provided.
这是我正在使用的代码,我似乎无法找到问题......有什么想法吗?
from flask import *
from functools import wraps
app = Flask(__name__)
app.secret_key = 'secret key' #Use a random key generator
@app.route('/')
def home():
return render_template('home.html')
@app.route('/welcome')
def welcome():
return render_template('welcome.html')
def login_required(test):
@wraps(test)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return test(*args, **kwargs)
else:
flash('You need to login first.')
return redirect(url_for('log'))
return wrap
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect (url_for('log'))
@app.route('/hello')
@login_required
def hello():
return render_template('hello.html')
@app.route('/log', methods=['GET', 'POST'])
def log():
error = None
if request.method =='POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = 'Invaled Credentials. Please try again.'
else:
session['logged_in'] = True
return redirect(url_for('hello'))
return render_template('log.html', error=error)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000, debug=True)
答案 0 :(得分:14)
您将return wrap
行缩进太多,现在您的装饰器返回None
值。最后一行是Unindent:
def login_required(test):
@wraps(test)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return test(*args, **kwargs)
else:
flash('You need to login first.')
return redirect(url_for('log'))
return wrap
异常指向@login_required
行,因为 next 装饰器@app.route('/hello')
在应用于@login_required
的输出时抛出异常。显式抛出AssertionError
异常,因为路径装饰器为函数传递了None
值。