Login

Header view decorators

Author:
ydm
Posted:
February 19, 2013
Language:
Python
Version:
1.4
Tags:
views view decorator headers decorators header
Score:
1 (after 1 ratings)

This file includes two Django view decorators header and headers that provide an easy way to set response headers.

Also, because I have to work with a lot of cross domain requests, I include few shortcuts for convenience to set the Access-Control-Allow-Origin header appropriately.

 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 8 years, 1 month ago
  2. Decorator for enabling views only when developing by damd 4 years, 12 months ago
  3. SWFUpload auth decorator by debrice 6 years, 5 months ago
  4. view by view basic authentication decorator by Scanner 8 years, 2 months ago
  5. Decorating URL includes by cotton 3 years, 11 months ago

Comments

Please login first before commenting.