Header view decorators

 1
 2
 3
 4
 5
 6
 7
 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
# -*- coding: utf-8 -*-

from functools import wraps

from django.utils.decorators import available_attrs


def header(name, value):
    # View decorator that sets a response header.
    # 
    # Example:
    # @header('X-Powered-By', 'Django')
    # def view(request, ...):
    #     ....
    #
    # For class-based views use:
    # @method_decorator(header('X-Powered-By', 'Django'))
    # def get(self, request, ...)
    #     ...
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            response = func(request, *args, **kwargs)
            response[name] = value
            return response
        return inner
    return decorator


def headers(header_map):
    # View decorator that sets multiple response headers.
    # 
    # Example:
    # @headers({'Connection': 'close', 'X-Powered-By': 'Django'})
    # def view(request, ...):
    #     ....
    #
    # For class-based views use:
    # @method_decorator(headers({'Connection': 'close',
    #                            'X-Powered-By': 'Django'})
    # def get(self, request, ...)
    #     ...
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            response = func(request, *args, **kwargs)
            for k in header_map:
                response[k] = header_map[k]
            return response
        return inner
    return decorator


allow_origin = lambda origin: header('Access-Control-Allow-Origin', origin)
allow_origin_all = allow_origin('*')

More like this

  1. HTTP headers view decorator by dottedmag 6 years, 10 months ago
  2. Decorator for enabling views only when developing by damd 3 years, 8 months ago
  3. SWFUpload auth decorator by debrice 5 years, 2 months ago
  4. view by view basic authentication decorator by Scanner 6 years, 11 months ago
  5. Decorating URL includes by cotton 2 years, 7 months ago

Comments

justinguru (on July 5, 2013):

Thanks! Lookboard is marketplace for wholesale modern furniture

#

(Forgotten your password?)