Request-Aware Code in Google App Engine — os.envir

2019-04-13 20:45发布

In GAE, you can say users.get_current_user() to get the currently logged-in user implicit to the current request. This works even if multiple requests are being processed simultaneously -- the users module is somehow aware of which request the get_current_user function is being called on behalf of. I took a look into the code of the module in the development server, and it seems to be using os.environ to get the user email and other values associated to the current request.

Does this mean that every request gets an independent os.environ object?

I need to implement a service similar to users.get_current_user() that would return different values depending on the request being handled by the calling code. Assuming os.environ is the way to go, how do I know which variable names are already being used (or reserved) by GAE?

Also, is there a way to add a hook (or event handler) that gets called before every request?

1条回答
我想做一个坏孩纸
2楼-- · 2019-04-13 20:54

As the docs say,

A Python web app interacts with the App Engine web server using the CGI protocol.

This basically means exactly one request is being served at one time within any given process (although, differently from real CGI, one process can be serially reused for multiple requests, one after the other, if it defines main functions in the various modules to which app.yaml dispatches). See also this page, and this one for documentation of the environment variables CGI defines and uses.

The hooks App Engine defines are around calls at the RPC layer, not the HTTP requests. To intercept each request before it gets served, you could use app.yaml to redirect all requests to a single .py file and perform your interception in that file's main function before redirecting (or, you could call your hook at the start of the main in every module you're using app.yaml to dispatch to).

查看更多
登录 后发表回答