简体   繁体   中英

Response from before_request

In my app I am trying to check if user is authorised to access the resource, for example when user requests to url api/proxy .

I use before_request to call checking function

 @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

The functionality of access checking is tested, I raise exception when access is not granted. Even in server log I can see "excepting". Return statement dont stop the execution process.

But the code dont stop execution and continues to proxy_get function

@get('/api/proxy')
def proxy_get():
    response = proxyService.get()
    return json.dumps({"Response" : response})

Is there any way to stop request handling in before_request function, or am I just messing something up? Whats the proper solution?

How do I set status code to that response? I tried

response.status_code(401)

but it didnt work. I was getting error TypeError: 'int' object is not callable

You should probably create a controller for Access denied and then modify the request to redirect to that controller. So, your code would look something like this:

@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

I have actually never used Bottle, so this might not the best way of doing it but it worked with simple test code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM