在我的应用中,我试图检查用户是否有权访问资源,例如当用户请求url api / proxy 时。
我使用before_request来调用检查函数
@hook('before_request')
def check_permission():
securityService = SecurityService(db=db)
try:
securityService.check_access_permission(request)
except Exception as e:
print("excepting")
return json.dumps({'Error': str(e)})
// stop execution here
测试访问检查的功能,我在未授予访问权限时引发异常。即使在服务器日志中,我也能看到"除了"。返回语句不要停止执行过程。
但代码不会停止执行并继续执行proxy_get函数
@get('/api/proxy')
def proxy_get():
response = proxyService.get()
return json.dumps({"Response" : response})
有没有办法在before_request函数中停止请求处理,或者我只是弄乱了什么?什么是正确的解决方案?
如何将状态代码设置为该响应? 我试过了
response.status_code(401)
但它没有用。我收到错误TypeError:' int'对象不可调用
答案 0 :(得分:1)
您应该为拒绝访问创建一个控制器,然后修改请求以重定向到该控制器。所以,你的代码看起来像这样:
@hook('before_request')
def check_permission():
securityService = SecurityService(db=db)
try:
securityService.check_access_permission(request)
except Exception as e:
request.environ['PATH_INFO'] = '/error_401'
@route('/error_401')
response.body = json.dumps({'Error': str(e)}
response.status = 401
return response
我实际上从未使用过Bottle,所以这可能不是最好的方法,但它适用于简单的测试代码。