-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This setting, which is set to `True` by default, will determine whether the instance is to be read-only. The `protected_methods_middleware` function is added as middleware to the application. If the `read_only` setting is `True` and the request method is `DELETE`, `PATCH`, `POST` or `PUT`, a `405 Method Not Allowed` response is returned.
- Loading branch information
Showing
4 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# -*- coding: utf-8 -*- | ||
"""Module with middleware.""" | ||
from fastapi import Request | ||
from fastapi.encoders import jsonable_encoder | ||
from fastapi.responses import JSONResponse | ||
|
||
from .config import Settings, get_settings | ||
|
||
|
||
async def protected_methods_middleware(request: Request, call_next): | ||
"""Middleware that will return a 405 if the instance is read only and the request method is mutating. | ||
Mutating request methods are `DELETE`, `PATCH`, `POST`, `PUT`. | ||
""" | ||
settings: Settings = get_settings() | ||
|
||
if settings.read_only and request.method in {"DELETE", "PATCH", "POST", "PUT"}: | ||
return JSONResponse( | ||
status_code=405, | ||
content=jsonable_encoder({"reason": "This instance is read-only."}), | ||
media_type="application/json", | ||
) | ||
|
||
return await call_next(request) |