Last active
July 19, 2020 01:41
-
-
Save ydm/4985159 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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('*') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment