make me a python reverse proxy
- User
make me a python reverse proxy
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
make me a python reverse proxy
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating a simple reverse proxy in Python can be done using the http.server module for handling HTTP requests and forwarding them to another server. Below is an example of a basic reverse proxy using Python:
import http.server
import socketserver
import urllib.request
# Define the address and port for your proxy
PROXY_HOST = 'localhost'
PROXY_PORT = 8080
# Define the address of the server you want to forward requests to
TARGET_HOST = 'example.com'
TARGET_PORT = 80
class ProxyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
# Forward the request to the target server
forwarded_url = f'http://{TARGET_HOST}:{TARGET_PORT}{self.path}'
self.send_response(200)
self.end_headers()
# Send the response back to the client
with urllib.request.urlopen(forwarded_url) as response:
self.copyfile(response, self.wfile)
def do_POST(self):
# Forward the POST request just like GET
forwarded_url = f'http://{TARGET_HOST}:{TARGET_PORT}{self.path}'
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
req = urllib.request.Request(forwarded_url, data=post_data, headers=self.headers)
with urllib.request.urlopen(req) as response:
self.send_response(response.getcode())
self.send_header('Content-type', response.info().get_content_type())
self.end_headers()
self.copyfile(response, self.wfile)
# Set up the server
with socketserver.TCPServer((PROXY_HOST, PROXY_PORT), ProxyHTTPRequestHandler) as httpd:
print(f"Serving at: http://{PROXY_HOST}:{PROXY_PORT}")
httpd.serve_forever()
To use this script:
TARGET_HOST and TARGET_PORT with the host and port of the server you want to forward requests to.http://localhost:8080 (or whatever PROXY_HOST and PROXY_PORT you set) to have requests forwarded to the target server.Please note that this is a very simple example and lacks many features that a production-ready reverse proxy should have, such as HTTPS support, header manipulation, error handling, and performance optimizations. For a production environment, you should consider using established reverse proxy software like Nginx, HAProxy, or Apache with mod_proxy, or use a more complete Python solution like mitmproxy or reverse-proxy.