2

I have implemented a code to calculate api time.

@api.app.before_request
def before_request():
    g.request_start_time = time.time()

@api.app.after_request
def after_request():
    elapsed = time.time() - g.request_start_time ------> Error here.

I am having error for ~1-2% api calls.

Error:

'_AppCtxGlobals' object has no attribute 'request_start_time'

I am not able to debug this. This can only happen if :

  1. the api does not pass through before_request function.
  2. the global context get reset in between the code.

First seems not to be happen as every api request should pass the before_request function. I am not able to find when the second case can occur. What are the scenarios when the global context get reset in between call.

Is there anything I am missing here ?

EDIT:

I have been observing the cases when this error is occurring and found the similarity that all calls were having 400 BAD REQUEST. But I am still not able to get the root cause of this.

Sunny Jain
  • 514
  • 2
  • 15

1 Answers1

0

I had a similar issue and is due because you called a variable g, so flask confuse it with the global application context also called g.

Have a look here: https://flask.palletsprojects.com/en/1.1.x/api/#flask.ctx._AppCtxGlobals

Creating an app context automatically creates this object, which is made available as the g proxy.

So try renaming your g variable in g.request_start_time = time.time()that you probably inherit from somewhere else.

If you are referring the flask context and having error correlated to 404 requests, it might be that when you call after_request() it does not find any attribute g.request_start_time , maybe because if requests fail the attribute is not created.

user305883
  • 1,635
  • 2
  • 24
  • 48