Performance: Handling different HTTP methods
This affects server response time and client perceived interaction speed by how efficiently the server processes different HTTP methods.
from django.views.decorators.http import require_http_methods @require_http_methods(["GET", "POST"]) def my_view(request): if request.method == 'GET': data = cached_db_query() return HttpResponse(data) elif request.method == 'POST': data = cached_db_query() return HttpResponse(data)
def my_view(request): if request.method == 'GET': # process GET data = expensive_db_query() return HttpResponse(data) elif request.method == 'POST': # process POST data = expensive_db_query() return HttpResponse(data) else: return HttpResponseNotAllowed(['GET', 'POST'])
| Pattern | Server Processing | Network Delay | Client Responsiveness | Verdict |
|---|---|---|---|---|
| Repeated expensive queries per method | High CPU and DB load | Longer wait | Slower INP | [X] Bad |
| Method decorators with caching | Reduced CPU and DB load | Shorter wait | Faster INP | [OK] Good |
request object helps you determine if the HTTP method is GET or POST inside a view?request object contains details about the HTTP request, including the method used.request.method holds the HTTP method as a string like 'GET' or 'POST'.@require_http_methods to restrict allowed HTTP methods on views.["GET", "POST"].from django.http import HttpResponse
def my_view(request):
if request.method == 'GET':
return HttpResponse('This is a GET request')
elif request.method == 'POST':
return HttpResponse('This is a POST request')request.method is 'GET' or 'POST' and returns corresponding responses.'This is a POST request' wrapped in an HttpResponse.def example_view(request):
if request.method = 'GET':
return HttpResponse('GET request')
elif request.method == 'POST':
return HttpResponse('POST request')request.method = 'GET' which is an assignment, not a comparison.== to compare values, like request.method == 'GET'.@require_http_methods decorator automatically restricts allowed HTTP methods and returns 405 if not allowed.@csrf_exempt is unrelated to method restriction; raising Http404 is incorrect for method errors.Pass the test and this pattern moves unknown