Created
November 17, 2019 22:43
-
-
Save adamghill/9d8e070d6058f4fff45d8313595863c5 to your computer and use it in GitHub Desktop.
Middleware to add method properties to Django's request object instead of string comparisons
This file contains hidden or 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
class RequestMethodMiddleware: | |
""" | |
Add request method as properties to the request object. | |
Example: `request.is_post` instead of `request.method == "POST"` | |
""" | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def __call__(self, request): | |
setattr(request, "is_post", request.method == "POST") | |
setattr(request, "is_get", request.method == "GET") | |
setattr(request, "is_patch", request.method == "PATCH") | |
setattr(request, "is_head", request.method == "HEAD") | |
setattr(request, "is_put", request.method == "PUT") | |
setattr(request, "is_delete", request.method == "DELETE") | |
setattr(request, "is_connect", request.method == "CONNECT") | |
setattr(request, "is_trace", request.method == "TRACE") | |
response = self.get_response(request) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment