Last active
April 15, 2024 11:43
-
-
Save JustinTArthur/5710254 to your computer and use it in GitHub Desktop.
A Django 1.4+ view function that acts as a reverse proxy. Great for testing locally or for using as a starting point to code that needs to cache or manipulate the proxied response. If one needs to proxy in production without any response manipulation, performing this in the web container (like nginx or apache) would be recommended instead of thi…
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
from django.views.decorators.csrf import csrf_exempt | |
@csrf_exempt | |
def reverse_proxy(request): | |
""" | |
Reverse proxy for a remote service. | |
""" | |
path = request.get_full_path() | |
#Optionally, rewrite the path to fit whatever service we're proxying to. | |
url = "http://%s%s" % ("my_server.lol:9200", path) | |
import requests | |
requestor = getattr(requests, request.method.lower()) | |
proxied_response = requestor(url, data=request.body, files=request.FILES) | |
from django.http.response import HttpResponse | |
response = HttpResponse(proxied_response.content, content_type=proxied_response.headers.get('content-type')) | |
for header_key, header_value in proxied_response.headers.iteritems(): | |
response[header_key] = header_value | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment