How to redirect to an external url with parameters and POST method? How to redirect to an external url with parameters and POST method? flask flask

How to redirect to an external url with parameters and POST method?


Sending a 307 status code instead of 302 should tell the browser to preserve the used HTTP method and thus have the behavior you're expecting. Your call to redirect would then look like this:

@mod.route('/payment/', methods=['GET', 'POST'])def payment():    if request.method != "POST":        return render_template('form.html')    form = request.form    form_data = {'PAYEE_ACCOUNT': form['PAYEE_ACCOUNT'],                 'PAYEE_NAME': form['PAYEE_Name'],                 'PAYMENT_AMOUNT' : form['PAYMENT_AMOUNT']                 }    # Save Data    url = 'http://www.example.com'    return redirect(url, code=307)


You need to use flask.redirect

flask.redirect(location, code=302)

Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.

Parameters:
location – the location the response should redirect to. code – the redirect status code. defaults to 302.

Sample code:

import osfrom flask import Flask,redirectapp = Flask(__name__)@app.route('/')def hello():    return redirect("http://www.example.com", code=302)if __name__ == '__main__':    # Bind to PORT if defined, otherwise default to 5000.    port = int(os.environ.get('PORT', 5000))    app.run(host='0.0.0.0', port=port)

see the documentation on flask docs.


I've solved this problem by using JavaScript.

First, sending the data to server.

JavaScript code:

<script type="text/javascript">  var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};  $(function() {    $('#PAYMENT_METHOD').bind('click', function() {      $.getJSON($SCRIPT_ROOT +'/credit/save_transaction', {        PAYMENT_ID: $('input[name="PAYMENT_ID"]').val(),        PAYMENT_AMOUNT: $('input[name="PAYMENT_AMOUNT"]').val(),        SUGGESTED_MEMO: $('input[name="SUGGESTED_MEMO"]').val()      }, function(data) {         if (data.result == 'ok') {            $('#form_payment').submit();         }      });      return false;    });  });</script>

Then, saving the data and returning result.

View code:

@mod.route('/save_transaction', methods=['GET', 'POST'])def save_transaction():    follow_num = request.args.get('PAYMENT_ID')    amount = request.args.get('PAYMENT_AMOUNT')    memo = request.args.get('SUGGESTED_MEMO')    #Save Data    return jsonify(result='ok')