decorators.py 1.9 KB
Newer Older
1 2 3 4 5 6 7
"""
Middleware decorator for removing headers.
"""

from functools import wraps
from header_control import remove_headers_from_response, force_header_for_response

8

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
def remove_headers(*headers):
    """
    Decorator that removes specific headers from the response.
    Usage:
        @remove_headers("Vary")
        def myview(request):
            ...

    The HeaderControlMiddleware must be used and placed as closely as possible to the top
    of the middleware chain, ideally after any caching middleware but before everything else.

    This decorator is not safe for multiple uses: each call will overwrite any previously set values.
    """
    def _decorator(func):
        """
        Decorates the given function.
        """
        @wraps(func)
        def _inner(*args, **kwargs):
            """
            Alters the response.
            """
            response = func(*args, **kwargs)
            remove_headers_from_response(response, *headers)
            return response

        return _inner

    return _decorator


def force_header(header, value):
    """
    Decorator that forces a header in the response to have a specific value.
    Usage:
        @force_header("Vary", "Origin")
        def myview(request):
            ...

    The HeaderControlMiddleware must be used and placed as closely as possible to the top
    of the middleware chain, ideally after any caching middleware but before everything else.

    This decorator is not safe for multiple uses: each call will overwrite any previously set values.
    """
    def _decorator(func):
        """
        Decorates the given function.
        """
        @wraps(func)
        def _inner(*args, **kwargs):
            """
            Alters the response.
            """
            response = func(*args, **kwargs)
            force_header_for_response(response, header, value)
            return response

        return _inner

    return _decorator