Skip to content

Instantly share code, notes, and snippets.

@JustinTArthur
Last active April 15, 2024 11:43
Show Gist options
  • Save JustinTArthur/5710254 to your computer and use it in GitHub Desktop.
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…
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