简体   繁体   中英

Bottle server: HTTPResponse vs bottle.response

I have a bottle instance whose server is set to a multi-threaded http server with a threadpool.

We know one common way to for a bottle server to return from a route is

return HTTPResponse(status=200, body=json.dumps({'key':'value'})

I am also using an after_request hook, which tries to set some headers on the response by referring to bottle.response , and I found that inside the after_request hook code, it can no longer access that same HTTPResponse object, because whatever is referenced by bottle.response is a new response object. The object as returned by HTTPResponse is lost.

And my theory is that it's because bottle.response references LocalResponse() , and is therefore thread-local.

Assuming I cannot modify my after_request hook code, what can I do so that my after_request hook can still access the same HTTPResponse object?

I can think of 2 ways:

1) Instead of returning a new HTTPResponse , I just return a dictionary as the body:

return json.dumps({'key','value'})

But how can I return a status code other than 200 now?

2) Instead of returning a new HTTPResponse , do:

bottle.response.status = 200; bottle.response.body = json.dumps({'key':'value'}); return bottle.response

Is 2) thread-safe? Will it cause issues for multiple requests hitting the server and the returned responses get mixed up in the after_request hook?

Yes, using bottle.response is thread-safe, even in hooks.

NOTE: Personally, I prefer using Bottle's plugins instead of hooks - your plugin can receive the returned HTTPResponse object and act on it directly, which IMO is cleaner than relying on thread local "magic."

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