[英]Flask - Decorator for Basic Auth
I'm trying to create decorator which will redirect to specified path if not logged in.我正在尝试创建装饰器,如果未登录,它将重定向到指定的路径。
Decorator:装饰器:
def secured(path):
@wraps(path)
def wrapper(f, *args, **kwargs):
if 'loggedin' in session:
if session.get('loggedin'):
return f(*args, **kwargs)
else:
redirect(path)
else:
session['loggedin'] = False
redirect(path)
return wrapper
Login function:登录功能:
def val_cred(username, password):
return username == 'login' and password == 'password'
@app.route('/login', methods=['POST'])
def login():
auth = request.authorization
if not auth.username or not auth.password or not val_cred(auth.username, auth.password):
return 'bad credentials', 401
session['loggedin'] = True
return redirect("/hello")
Example of secured path:安全路径示例:
@app.route('/hello')
@secured('/')
def hello():
return 'you are logged in'
Before I created decorator with static path which takes no arguments and it worked well, so I thought it's syntax problem, but Flask states it's something else在我创建带有静态路径的装饰器之前,它不带任何参数并且运行良好,所以我认为这是语法问题,但 Flask 表示它是别的东西
Traceback (most recent call last):
File "C:/daftcode-flask/app.py", line 31, in <module>
@secured('/')
File "C:/daftcode-flask/app.py", line 14, in wrapper
if 'loggedin' in session:
...
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
How can I make it work properly?我怎样才能让它正常工作?
You have an mistake in secured
decorator.您在secured
装饰器中犯了一个错误。 You forgot to add one more function inside(see: def _secured(f)
):你忘了在里面再添加一个函数(见: def _secured(f)
):
def secured(path):
def _secured(f):
@wraps(path)
def __secured(*args, **kwargs):
# Note! I didn't check your functionality
if 'loggedin' in session:
if session.get('loggedin'):
return f(*args, **kwargs)
else:
redirect(path)
else:
session['loggedin'] = False
redirect(path)
return __secured
return _secured
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.