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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.