Skip to content
This repository was archived by the owner on Nov 19, 2024. It is now read-only.

Commit 633cf6f

Browse files
committed
Added doc and test for JSON overwrite of url params
1 parent 853c7a4 commit 633cf6f

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

flask_utils/decorators.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,33 @@ def example(name: str, age: int, is_student: bool, courses: List[str], grades: D
225225
* Optional
226226
* Union
227227
228+
.. warning::
229+
If a parameter exists both in the route parameters and in the JSON body,
230+
the value from the JSON body will override the route parameter. A warning
231+
is issued when this occurs.
232+
233+
:Example:
234+
235+
.. code-block:: python
236+
237+
from flask import Flask, request
238+
from typing import List, Dict
239+
from flask_utils.decorators import validate_params
240+
from flask_utils.errors import BadRequestError
241+
242+
app = Flask(__name__)
243+
244+
@app.route("/users/<int:user_id>", methods=["POST"])
245+
@validate_params()
246+
def create_user(user_id: int):
247+
print(f"User ID: {user_id}")
248+
return "User created"
249+
250+
...
251+
252+
requests.post("/users/123", json={"user_id": 456})
253+
# Output: User ID: 456
254+
228255
.. versionchanged:: 1.0.0
229256
The decorator doesn't take any parameters anymore,
230257
it loads the types and parameters from the function signature as well as the Flask route's slug parameters.

tests/test_validate_params.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,3 +565,17 @@ def test_max_depth(self, client):
565565
assert len(w) == 1
566566
assert issubclass(w[-1].category, SyntaxWarning)
567567
assert "Maximum depth of 4 reached." in str(w[-1].message)
568+
569+
570+
class TestJSONOverridesRouteParams:
571+
@pytest.fixture(autouse=True)
572+
def setup_routes(self, flask_client):
573+
@flask_client.post("/users/<int:user_id>")
574+
@validate_params()
575+
def create_user(user_id: int):
576+
return f"{user_id}"
577+
578+
def test_valid_request(self, client):
579+
response = client.post("/users/123", json={"user_id": 456})
580+
assert response.status_code == 200
581+
assert response.text == "456"

0 commit comments

Comments
 (0)