본문 바로가기

web/Django

django cross domain allow middleware

도저히 django-cors-headers 가 설치 되지 않아서 미들웨어로 처리 했다. (이유는 아직도 모른다.)

 

from django import http

try:
    import settings
    XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
    XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
    XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS
except:
    XS_SHARING_ALLOWED_ORIGINS = ''
    XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
    XS_SHARING_ALLOWED_HEADERS = []


class XsSharing(object):
    def __init__(self, get_response=None) -> None:
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_request(self, request):

        if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
            response = http.HttpResponse()
            response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS
            response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS)
            response['Access-Control-Allow-Headers'] = ",".join(XS_SHARING_ALLOWED_HEADERS)
            return response

        return None

    def process_response(self, request, response):
        if response.has_header('Access-Control-Allow-Origin'):
            return response

        response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS
        response['Access-Control-Allow-Methods'] = ",".join(XS_SHARING_ALLOWED_METHODS)

        return response

 

settings.py에 위의 미들웨어를 선언해준다. 

MIDDLEWARE = [
    'middlewares.middleware.django-crossdomainxhr-middleware.XsSharing',
    ....
]

 

디폴트로 모두 허용이므로 settings.py에 파라미터를 추가해준다.

XS_SHARING_ALLOWED_ORIGINS = '*' # 허용하는 도메인 콤마(,)로 구분 ex: www.google.com, *.naver.com
XS_SHARING_ALLOWED_METHODS = "POST, GET, OPTIONS, PUT, DELETE"

 

 

참고: https://gist.github.com/jessykate/2941258