Need to forward income request to different ports on localhost due to limitation

Hi Prodigy team, so due to internal limitation I can only expose server port 80 to annotators. However I need two Prodigy jobs to be done in parallel, one running on localhost:8080, one on localhost:8081 on my server.

I know there is a way to code a simple proxy server that can listen on a fixed port (e.g. 80), and then forward incoming requests to the appropriate application running on a different port on localhost.

I tried this script but got "The browser (or proxy) sent a request that this server could not understand." error. Is there a proper way to proxy server such that I can achieve my goal?

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

@app.route('/app1', methods=['GET', 'POST', 'PUT','DELETE'])
def app1():
    target_url = "http://0.0.0.0:8080"
    response = requests.request(
        method=request.method,
        url=target_url,
        headers={key: value for (key, value) in request.headers if key != 'host'},
        json=request.json,
        data=request.data,
        params=request.args,
        cookies=request.cookies,
        allow_redirects=False)
    if response.ok:
        return jsonify(response.json()), response.status_code
    else:
        return jsonify({"error_message": response.text}), response.status_code

@app.route('/app2', methods=['GET', 'POST', 'PUT','DELETE'])
def app2():
    target_url = "http://0.0.0.0:8081"
    response = requests.request(
        method=request.method,
        url=target_url,
        headers={key: value for (key, value) in request.headers if key != 'host'},
        json=request.json,
        data=request.data,
        params=request.args,
        cookies=request.cookies,
        allow_redirects=False)
    if response.ok:
        return jsonify(response.json()), response.status_code
    else:
        return jsonify({"error_message": response.text}), response.status_code
    
if __name__ == '__main__':
    app.run()

I'm also not a proxy expert but I think the issue here is that you're wrapping everything in jsonify in your responses. That doesn't work here because some of the responses will be HTML instead of JSON.

In general, I'd also recommend a proxy tool over Flask for this use-case. Something like nginx or treafik should be a better tool for the job.

If you're interested in exploring that, you may appreciate Matt's response here:

1 Like