2005-10-09 08:55:08 +08:00
|
|
|
"""
|
2005-10-28 09:30:30 +08:00
|
|
|
Decorators for views based on HTTP headers.
|
2005-10-09 08:55:08 +08:00
|
|
|
"""
|
|
|
|
|
2008-02-25 14:02:35 +08:00
|
|
|
try:
|
|
|
|
from functools import wraps
|
|
|
|
except ImportError:
|
|
|
|
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
|
|
|
|
|
2005-10-09 08:55:08 +08:00
|
|
|
from django.utils.decorators import decorator_from_middleware
|
|
|
|
from django.middleware.http import ConditionalGetMiddleware
|
2006-06-20 11:17:57 +08:00
|
|
|
from django.http import HttpResponseNotAllowed
|
2005-10-09 08:55:08 +08:00
|
|
|
|
|
|
|
conditional_page = decorator_from_middleware(ConditionalGetMiddleware)
|
2005-10-28 09:30:30 +08:00
|
|
|
|
|
|
|
def require_http_methods(request_method_list):
|
|
|
|
"""
|
|
|
|
Decorator to make a view only accept particular request methods. Usage::
|
2006-06-20 11:17:57 +08:00
|
|
|
|
2005-10-28 09:30:30 +08:00
|
|
|
@require_http_methods(["GET", "POST"])
|
|
|
|
def my_view(request):
|
|
|
|
# I can assume now that only GET or POST requests make it this far
|
2006-06-20 11:17:57 +08:00
|
|
|
# ...
|
|
|
|
|
2006-06-20 12:34:13 +08:00
|
|
|
Note that request methods should be in uppercase.
|
2005-10-28 09:30:30 +08:00
|
|
|
"""
|
|
|
|
def decorator(func):
|
|
|
|
def inner(request, *args, **kwargs):
|
2006-06-20 12:34:13 +08:00
|
|
|
if request.method not in request_method_list:
|
2006-06-20 11:17:57 +08:00
|
|
|
return HttpResponseNotAllowed(request_method_list)
|
2005-10-28 09:30:30 +08:00
|
|
|
return func(request, *args, **kwargs)
|
2008-02-25 14:02:35 +08:00
|
|
|
return wraps(func)(inner)
|
2005-10-28 09:30:30 +08:00
|
|
|
return decorator
|
|
|
|
|
|
|
|
require_GET = require_http_methods(["GET"])
|
|
|
|
require_GET.__doc__ = "Decorator to require that a view only accept the GET method."
|
|
|
|
|
|
|
|
require_POST = require_http_methods(["POST"])
|
|
|
|
require_POST.__doc__ = "Decorator to require that a view only accept the POST method."
|