How to redirect to an external URL with dynamic POST data

Viewed 167

I have created a proxy to test my microservices locally with Flask. I need to redirect requests with POST data dynamically, meaning my proxy has to forward the POST data without knowing the name of the parameters. My code looks something like this

@app.route('/', defaults={'path': ''}, methods=HTTP_METHODS)
@app.route('/<path:path>', methods=HTTP_METHODS)
def redirect_request(path):
    for i in routes:
        if i[0] == '/' + path:
            if flask.request.method == 'POST':
                return flask.redirect(i[1] + i[0], code=307)
            return flask.redirect(i[1] + i[0])
    return flask.Response('not ok')

I tried to pass flask.request.form as **kwargs in flask.redirect(), but it doesn't work. Any idea how I can do it?

1 Answers

You don't need to do anything with the form data, returning the redirect is enough. The 307 redirect code instructs the user-agent to repeat the query to the new address while keeping all of the parameters of the query as they are. That means, for example, that if the original request was a POST and contained form fields, then the new request will also be a POST and will contain those same form fields and values. Here's an example:

import flask

app = flask.Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def redirect_request():
    if flask.request.method == 'GET':
        return '''
<form method="POST">
  <input name="field1" value="Field 1">
  <input name="field2" value="Field 2">
  <input name="field3" value="Field 3">
  <input name="field4" value="Field 4">
  <input name="field5" value="Field 5">
  <input type="submit">
</form>'''
    else:
        return flask.redirect('https://httpbin.org/post', code=307)

app.run('0.0.0.0', 5000, debug=True)
Related