Django reverse proxy

GisangLee·2022년 10월 12일
0

django

목록 보기
23/35

1. django-revproxy

쉽게 말해 하나의 api 엔드포인트를 통해 path를 판별하여 해당 path에 맞는 api로 매칭해주는 것.

pip install django-revproxy

2. 사용법

from django.urls import path, re_path

from .views import CustomProxyViews

urlpatterns = [
    re_path(r"^(?P<path>.*)$", CustomProxyViews.as_view()),
]
  • views.py
import json
from wsgiref.util import is_hop_by_hop

from django.conf import settings
from django.contrib import auth
from django.http import HttpResponse
from django.shortcuts import redirect
from revproxy.response import get_django_response
from revproxy.utils import cookie_from_string
from revproxy.views import ProxyView


class CustomProxyViews(ProxyView):
    upstream = "https://외부 API"

    def get_request_headers(self):
        # Call super to get default headers
        headers = super(CustomProxyViews, self).get_request_headers()
        headers["Accept-Encoding"] = "gzip"
        headers["Accept"] = "application/json"
        headers["Content-Type"] = "application/json"
        return headers

    def dispatch(self, request, path):
        self.request_headers = self.get_request_headers()

        redirect_to = super(CustomProxyViews, self)._format_path_to_redirect(request)

        if redirect_to:
            return redirect(redirect_to)

        proxy_response = super(CustomProxyViews, self)._created_proxy_response(request, path)

        super(CustomProxyViews, self)._replace_host_on_redirect_location(request, proxy_response)
        super(CustomProxyViews, self)._set_content_type(request, proxy_response)

        response = HttpResponse(
            proxy_response.data, status=proxy_response.status, content_type=proxy_response.headers.get("Content-Type")
        )

        for header, value in proxy_response.headers.items():
            if is_hop_by_hop(header) or header.lower() == "set-cookie":
                continue

            response[header.title()] = value

        cookies = proxy_response.headers.getlist("set-cookie")

        for cookie_string in cookies:
            cookie_dict = cookie_from_string(cookie_string, strict_cookies=self.strict_cookies)

            # if cookie is invalid cookie_dict will be None
            if cookie_dict:
                response.set_cookie(**cookie_dict)

        return response
profile
포폴 및 이력서 : https://gisanglee.github.io/web-porfolio/

0개의 댓글