You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.py 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. """
  2. Decorators for views based on HTTP headers.
  3. """
  4. from calendar import timegm
  5. from functools import wraps
  6. from django.http import HttpResponseNotAllowed
  7. from django.middleware.http import ConditionalGetMiddleware
  8. from django.utils.cache import get_conditional_response
  9. from django.utils.decorators import decorator_from_middleware
  10. from django.utils.http import http_date, quote_etag
  11. from django.utils.log import log_response
  12. conditional_page = decorator_from_middleware(ConditionalGetMiddleware)
  13. def require_http_methods(request_method_list):
  14. """
  15. Decorator to make a view only accept particular request methods. Usage::
  16. @require_http_methods(["GET", "POST"])
  17. def my_view(request):
  18. # I can assume now that only GET or POST requests make it this far
  19. # ...
  20. Note that request methods should be in uppercase.
  21. """
  22. def decorator(func):
  23. @wraps(func)
  24. def inner(request, *args, **kwargs):
  25. if request.method not in request_method_list:
  26. response = HttpResponseNotAllowed(request_method_list)
  27. log_response(
  28. 'Method Not Allowed (%s): %s', request.method, request.path,
  29. response=response,
  30. request=request,
  31. )
  32. return response
  33. return func(request, *args, **kwargs)
  34. return inner
  35. return decorator
  36. require_GET = require_http_methods(["GET"])
  37. require_GET.__doc__ = "Decorator to require that a view only accepts the GET method."
  38. require_POST = require_http_methods(["POST"])
  39. require_POST.__doc__ = "Decorator to require that a view only accepts the POST method."
  40. require_safe = require_http_methods(["GET", "HEAD"])
  41. require_safe.__doc__ = "Decorator to require that a view only accepts safe methods: GET and HEAD."
  42. def condition(etag_func=None, last_modified_func=None):
  43. """
  44. Decorator to support conditional retrieval (or change) for a view
  45. function.
  46. The parameters are callables to compute the ETag and last modified time for
  47. the requested resource, respectively. The callables are passed the same
  48. parameters as the view itself. The ETag function should return a string (or
  49. None if the resource doesn't exist), while the last_modified function
  50. should return a datetime object (or None if the resource doesn't exist).
  51. The ETag function should return a complete ETag, including quotes (e.g.
  52. '"etag"'), since that's the only way to distinguish between weak and strong
  53. ETags. If an unquoted ETag is returned (e.g. 'etag'), it will be converted
  54. to a strong ETag by adding quotes.
  55. This decorator will either pass control to the wrapped view function or
  56. return an HTTP 304 response (unmodified) or 412 response (precondition
  57. failed), depending upon the request method. In either case, the decorator
  58. will add the generated ETag and Last-Modified headers to the response if
  59. the headers aren't already set and if the request's method is safe.
  60. """
  61. def decorator(func):
  62. @wraps(func)
  63. def inner(request, *args, **kwargs):
  64. # Compute values (if any) for the requested resource.
  65. def get_last_modified():
  66. if last_modified_func:
  67. dt = last_modified_func(request, *args, **kwargs)
  68. if dt:
  69. return timegm(dt.utctimetuple())
  70. # The value from etag_func() could be quoted or unquoted.
  71. res_etag = etag_func(request, *args, **kwargs) if etag_func else None
  72. res_etag = quote_etag(res_etag) if res_etag is not None else None
  73. res_last_modified = get_last_modified()
  74. response = get_conditional_response(
  75. request,
  76. etag=res_etag,
  77. last_modified=res_last_modified,
  78. )
  79. if response is None:
  80. response = func(request, *args, **kwargs)
  81. # Set relevant headers on the response if they don't already exist
  82. # and if the request method is safe.
  83. if request.method in ('GET', 'HEAD'):
  84. if res_last_modified and not response.has_header('Last-Modified'):
  85. response['Last-Modified'] = http_date(res_last_modified)
  86. if res_etag:
  87. response.setdefault('ETag', res_etag)
  88. return response
  89. return inner
  90. return decorator
  91. # Shortcut decorators for common cases based on ETag or Last-Modified only
  92. def etag(etag_func):
  93. return condition(etag_func=etag_func)
  94. def last_modified(last_modified_func):
  95. return condition(last_modified_func=last_modified_func)