Issue
Request keep repeating when return redirect.
I made a button to send delete request to which its going to delete session data with key 'order_list', but it keep doing redirect until it stopped by the browser
cart_order.html
<script>
function clearQuery() {
fetch("/cart", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then((data) => {
console.log("All orders have been deleted");
})
.catch((error) => {
console.error("Error deleting orders", error);
});
}
</script>
<button onclick="clearQuery()">Clear Query</button>
Flask
from flask import Flask, render_template, redirect, url_for, session, request
app = Flask(__name__)
app.secret_key = 'THIS_IS_SECRET_KEY'
@app.route('/cart', methods=["GET", "DELETE"])
def cart():
# for demonstration
session['order_list'] = {
'order_1': {
'marker': True,
'color': 'blue'
},
'order_2': {
'marker': True,
'color': 'red'
},
'order_3': {
'marker': True,
'color': 'blue'
}
}
if request.method == "GET":
if 'order_list' in session:
print(session['order_list'])
else:
print(session)
return render_template('cart_order.html')
elif request.method == "DELETE":
session.pop('order_list')
session.modified = True
return redirect(url_for('cart'))
if __name__ == "__main__":
app.run(debug=True)
I'd like the session data with key 'order_list' get deleted, and then redirect back to itself with GET request, and print session which now should be empty
Solution
please check from wikipedia article:
... For this reason, HTTP/1.1 (RFC 2616) added the new status codes 303 and 307 to disambiguate between the two behaviours, with 303 mandating the change of request type to GET, and 307 preserving the request type as originally sent.
So according to this, adding in your redirect code=303
will do the trick:
return redirect(url_for('cart'), code=303)
And indeed it works (tested on Firefox). While Codes 302 and 307 enter the endless loop you experienced.
Answered By - ilias-sp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.