1

对于 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')

这似乎有点多余,因为我想保护每个请求,如果我忘记调用它可能会失败。有没有更好的办法?

4

1 回答 1

6

我认为您正在寻找一个装饰器,它要求只有在用户登录时才能访问路由。就像下面的例子一样,@require_uid是一个装饰器,你可以在需要用户登录的任何功能周围使用它。Flask 有一个login_required 装饰器

使用装饰器要求使用 bottle.py 登录

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")
于 2012-12-30T01:42:40.937 回答