Last active
August 6, 2020 13:40
-
-
Save baxeico/fdec989a5e5ea0df0d0814edb4462b15 to your computer and use it in GitHub Desktop.
Simple mixin to add CORS headers in a Django View
This file contains hidden or 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
from django.http import HttpResponse | |
class AllowCORSMixin(object): | |
def add_access_control_headers(self, response): | |
response["Access-Control-Allow-Origin"] = "*" | |
response["Access-Control-Allow-Methods"] = "GET, OPTIONS" | |
response["Access-Control-Max-Age"] = "1000" | |
response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type" | |
def options(self, request, *args, **kwargs): | |
response = HttpResponse() | |
self.add_access_control_headers(response) | |
return response |
This file contains hidden or 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
from django.views.generic import View | |
from braces.views import AjaxResponseMixin, JSONResponseMixin | |
class JsonView(JSONResponseMixin, AjaxResponseMixin, AllowCORSMixin, View): | |
def get_ajax(self, request, *args, **kwargs): | |
# ... get some data ... | |
response = self.render_json_response({ 'data': data }) | |
self.add_access_control_headers(response) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment