falconry / falcon

The no-magic web data plane API and microservices framework for Python developers, with a focus on reliability, correctness, and performance at scale.
https://falcon.readthedocs.io/en/stable/
Apache License 2.0
9.51k stars 937 forks source link

Would it be useful to have `req.get_header_as_int()`? #2060

Closed vytas7 closed 1 year ago

vytas7 commented 2 years ago

Sometimes it might be handy to easily get a header's value as int, where validation errors would automatically result in an HTTP 400, along the lines of req.get_header_as_datetime & req.get_param_as_int.

CaselIT commented 2 years ago

can't say I ever needed it, but the it should be pretty straight forward. Mostly a test exercize

vytas7 commented 2 years ago

Actually, I needed it today -- hence the issue :rofl:

ardaasln commented 2 years ago

Hey @vytas7, I have been using falcon daily so I decided to contribute to it. This issue seems to be a good one for me to hop on initially to fully comprehend the repo. Let me know if you still believe that this is useful (which I never needed) so I can work on it

CaselIT commented 2 years ago

Hi @ardaasln

let's wait on @vytas7 opition, but re-reading this maybe we could have a more general get_header_as() method that takes the name of the header and a conversion function.

So one could use it as:

the method would basically check if the header exists call the function and raise a 400 if the function raises?

Not sure if this is too magical to be useful though. Thoughts?

edit: well we already have a get_header_as_datetime, so I guess something like this would be a bit of an outlier

vytas7 commented 2 years ago

Your idea is worth filing as a separate suggestion, although yeah, the framework already has many get_param_as_* and (not so many) get_header_as_* methods, so it may make sense to continue in the same vein.

Large projects probably want to use validation libraries on headers, params and media anyway.

I can understand that maybe this method is not needed at all. But if there is get_header_as_datetime(), maybe it makes sense to have get_header_as_int() too. Or should we wait until anyone actually needs it? (I have restructured the code in question, although I could have used this method if it existed.)

ardaasln commented 2 years ago

Even though it is not vital, for the sake of completeness and consistency I think it should be in there. One that is using get_param_as_int() unintentionally expects get_header_as_int()

vytas7 commented 1 year ago

Implemented in #2117