miguelgrinberg / microdot

The impossibly small web framework for Python and MicroPython.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to set headers for all responses (and errors)

damiencorpataux opened this issue · comments

Hello,

My project need all responses to have the header Access-Control-Allow-Origin: *.

Using @after_request works well for 2xx responses and @errorhandler(Exception) for Exceptions. But this does not apply to HTTPErrors (mainly 400, 404, 405, 500 etc).

Is there a way to set a single handler for any HTTPError (or better, for any response) ?

Okay, this is something I have no considered. Basically you want a catch-all handler for all the 4xx/5xx error codes. I'll look into it.

Here are thoughts:

  • Apply @after_request handlers to all responses (example) (i believe flask does that)

  • Allow @errorhandler(0) to apply the handler as fallback to all status codes of HTTPException, if a more specific handler does not exist (example)

Yes, I think the first option is what makes the most sense. The handler receives the response object, so it can check its attributes if it needs to know if this is a valid or error response. And for CORS support where it doesn't really matter you can just add the header(s) and forget about it.

After seeing how your PR caused some tests to fail I realized this change might also affect existing applications, so instead I have added a separate @after_error_request decorator. Let me know what you think.