[BUG] Request object used in the route is not the same object used for exception handling #1955
Answered
by
alex-oleshkevich
sevakharutyunyan
asked this question in
Potential Issue
-
ProblemIn this discussion we provide the script, requirements, and commands to run and test the app. from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.requests import Request
from pydantic import BaseModel, ValidationError
class RequestModel(BaseModel):
name: str
age: int
async def homepage(request: Request):
print(id(request))
request_json = await request.json()
_ = RequestModel(**request_json)
return JSONResponse({'hello': 'world'})
def bad_request(request: Request, exc: ValidationError):
print(id(request))
return JSONResponse(
content={"error": exc.errors()},
status_code=400,
)
exception_handlers = {
ValidationError: bad_request
}
app = Starlette(
debug=True,
routes=[Route('/', homepage, methods=["POST"])],
exception_handlers=exception_handlers
) Requiremets:
Command: uvicorn app:app Test: curl --request POST \
--url 'http://localhost:8000/?=' \
--header 'Content-Type: application/json' \
--data '{
"name": 12,
"age": "Arthur"
}
' |
Beta Was this translation helpful? Give feedback.
Answered by
alex-oleshkevich
Nov 18, 2022
Replies: 1 comment 1 reply
-
Yes, this is by design. There is a bunch of issues related to this topic. You can search for them for more information. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
sevakharutyunyan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, this is by design.
Request
class is just an API interface to ASGI scope. If you want to share data, userequest.state
object.For example,
request.state.request_id = 42
.There is a bunch of issues related to this topic. You can search for them for more information.