Currently, the BaseSessionBackend
handles serialization of custom types (such as Struct
, BaseModel
etc.) using the type encoders set by the user. However, when it deserializes the data, the user will not get back the types that was initially serialized but only a dictionary. This is a bit inconsistent and removes type safety and other IDE/editor benefits when accessing data from request.session
unless they manually convert the returned dictionary into a class or cast it into a TypedDict.
For example,
from msgspec import Struct
class Session(Struct):
user_id: int
user_role: Role
async def login(data: Credentials, request: Request, user_service: UserService) -> None:
user = await user_service.login_user(data)
# Here the `Session` gets serialized properly without issues.
request.set_session(Session(user.user_id, user.role))
async def some_view(request: Request) -> None:
# Current way since `request.session` returns a `dict[str, Any]` which is
# due to `BaseSessionBackend.deserialize_data` returning a dictionary.
session_dict = request.session
session = Session(**session_dict)
# Proposed way.
session = request.session
assert isinstance(session, Session) # True
It would be nice if the session config could be given a type to which the session middleware (or rather, the session backend) would deserialize the session data into.
No response
There may be some difficulty in making this backwards compatible if we want to make request.session
return a generic type since we would have to add another generic parameter to Request.
If this is not possible, users could do something like session = cast(Session, request.session)
and the breaking changes could be made in v3. This also may require changes in the API of BaseSessionBackend.deserialize_data
to allow it to take a Scope
in order to get the type decoders as done in BaseSessionBackend.serialize_data.
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too