Mah*_*oni 1 python authorization bottle
对于 Bottle 中的每个请求,我想通过 HTTP 身份验证检查该请求是否符合条件。我的想法是使用一个函数,它在每个@route函数开始时都会被调用。
def check_authentificaiton(requests):
auth = request.headers.get('Authorization')
credentials = parse_auth(auth)
if credentials[0] is not 'user' or credentials[1] is not 'password':
raise Exception('Request is not authorized')
Run Code Online (Sandbox Code Playgroud)
这似乎有点多余,因为我想保护每个请求,如果我忘记调用它可能会失败。有没有更好的办法?
我认为您正在寻找一个装饰器,该装饰器仅在用户登录时才要求访问路由。就像下面的例子一样,@require_uid是一个装饰器,你可以在需要用户登录的任何函数周围使用它。 Flask 有一个login_required 装饰器。
def require_uid(fn):
def check_uid(**kwargs):
cookie_uid = request.get_cookie('cookieName', secret='cookieSignature')
if cookie_uid:
# do stuff with a user object
return fn(**kwargs)
else:
redirect("/loginagain")
return check_uid
@route('/userstuff', method='GET')
@require_uid
@view('app')
def app_userstuff():
# doing things is what i like to do
return dict(foo="bar")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3546 次 |
| 最近记录: |