Skip to content

Instantly share code, notes, and snippets.

@adamghill
Created November 17, 2019 22:43
Show Gist options
  • Save adamghill/9d8e070d6058f4fff45d8313595863c5 to your computer and use it in GitHub Desktop.
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
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