sanic-org / sanic

Accelerate your web app development | Build fast. Run fast.
https://sanic.dev
MIT License
18.11k stars 1.55k forks source link

Add option for non snake_case query parameters in url_for #2974

Open mayushii21 opened 4 months ago

mayushii21 commented 4 months ago

Is there an existing issue for this?

Is your feature request related to a problem? Please describe.

Passing query parameters with keys that aren't snake_case in url_for is currently not possible, as python only allows underscores in function parameter names. However it is quite common for query parameters to be hyphenated. So for example, generating a url like http://server/posts/5?user-id=123 is currently not possible with url_for. Someone may even want to use camelCase for their parameter names.

Describe the solution you'd like

It would be nice if there were an additional parameter like hyphenate: bool = False or something that would do something like {k.replace('_', '-'): v for k, v in kwargs.items()} before encoding query parameters, as it is extremely common to separate query parameters with hyphens instead of underscores.

Or better yet, have an additional parameter query_params: Dict[str, Any] that accepts a dictionary of str: any pairs, and adds that as query parameters, which would also allow passing camelCase parameters (personally don't need this, but someone might), and just update the current kwargs with it

Additional context

The codebase I'm currently working on uses hyphens for query parameters, so either the entire codebase would need to be reworked, or I'd need to manually manipulate the string from url_for and add hyphenated query parameters to make things work as expected. Creating a built in option for handling this would be very helpful. The current functionality of implementing anything that is not a request parameter as a part of the query string should not be removed for backwards compatibility, but adding a query_params parameter would also serve the purpose of self documenting code more clearly

Tronic commented 4 months ago

Always converting underscores to hyphens seems the most reasonable, although noting that this cannot be done with url_for without breaking compatibility. It's been long proposed to introduce another method of constructing URLs (by @ahopkins) and making it anew would allow addressing not just this but also any other problems.

Adding another toggle in kwarg or global (app/blueprint) setting for compatibility is something I am not too fond of.

mayushii21 commented 4 months ago

both proposed additions would not break compatibility. But yeah, I've seen Adam mention on Discord that url_for is on his radar for a complete overhaul, so ig there's nothing to be done about it until then