Consolidating HTTP status codes
See original GitHub issueI have noticed that there is starlette.status
, which groups all status codes in one place. However, there are several places in the code where it’s using a number directly instead of the starlette.status
, e.g. when returning errors.
That said, I’m a big fan of the standard library’s nice little http.HTTPStatus
enum, which neatly groups all the status codes and their standard messages and descriptions, while at the same time keeps the integer functionality (truth be told, HTTP status codes are not really integers; we just treat them as such as it’s easy and clean).
So I’d like to propose doing a few minor refactorings in the Starlette code; I can easily make a PR myself, but I’d like to hear any comments on the idea first, in particular if there is any concrete reason for not using http.HTTPStatus
. My ideas are:
- Replace all integer values in
starlette.status
with the equivalentHTTPStatus
value; or even, possibly, completely replace them in the manner thatstarlette.status.HTTP is http.HTTPStatus
(this needs applying the change everywhere, but it shouldn’t be a problem if its just internal). - Replace all the integers used for status code with the corresponding
startlette.status
values. - Create a
HTTPStatus
-like enum for all the codes it does not cover – this especially goes for the WebSocket Close Codes – and apply them in the same manner as above.
Optionally, I would like to suggest a new PlainTextResponse
subclass specifically for errors, so in the case linked above it would be something like:
return HTTPErrorResponse(status.HTTP_405_METHOD_NOT_ALLOWED)
or, if the second approach in no. 1 above is used:
return HTTPErrorResponse(status.HTTP.METHOD_NOT_ALLOWED)
My main problem here is that it can be used for any type of response and not just errors; the solutions I can think of are:
- Trust the user and let them use it as they see fit (I would prefer this).
- Not trust the user and explicitly check if the status is >= 400; I’m not sure what is the general policy for Starlette in such cases.
OK, that’s it from me for now, looking forward to any thoughts and comments.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:4
- Comments:10 (5 by maintainers)
Top GitHub Comments
Very well, this seems like a solid compromise, I can do this PR.
Yeah, I’d suggest we tweak PlainTextResponse so that it gets a default status phrase from the stdlib http. We don’t need to change the status module here to deal with that tho.