How to remove parameters from url in Flask python

On my website, I have URLs that will have the following parameters:

example.com/magicpage/?p=10&d=somestuff 

Is there a way to remove these parameters after processing the request? Therefore, when the user clicks on the link, the parameters are passed, but the visible URL is simple:

 example.com/magicpage 

My code is:

 @app.route("/magicpage") def magicPage(): #parse parameters and do things #finish up #remove the trailing parameters in the url #return the rendered page 
+8
source share
2 answers

There are two ways to do this.

Option 1. Use the POST parameters, not GET.

If the parameters are passed through an HTML form, add method=post in the <form> and change your page from:

 @app.route("/magicpage") def magicPage(): param1 = request.args.get("param1") param2 = request.args.get("param2") 

so that:

 @app.route("/magicpage", methods=["POST"]) def magicPage(): param1 = request.form.get("param1") param2 = request.form.get("param2") 

There is no redirect above. The disadvantage is that if the user tries to update the received page, he will receive an unpleasant browser pop-up window about re-sending information:

Firefox refresh confirmation of a POST webpage

However, this is the most common way to transmit hidden parameters on the network.


Option 2. Redirect after processing the parameters.

This is a bit complicated, because since we are redirecting to the same page, we need to check whether they come to this page for the first time or the second.

The best way to do this is to use a mail request. This has the advantage that it does not have an update popup window, but it has the disadvantage that it does not give you options the next time the page is displayed, unless you save them in a session.

 @app.route("/magicpage", methods=["GET", "POST"]) def magicPage(): if request.method == 'POST': # process parameters redirect(request.path) if request.method == "GET": # render page 

In addition, you can simply check for one of the parameters as your indicator:

 @app.route("/magicpage", methods=["GET", "POST"]) def magicPage(): if request.form.get("param1", None) is not None: # process parameters redirect(request.path) else: # render page 
+7
source

You can use hidden form fields to pass parameters across multiple pages using POST .

 <input type="hidden" ...> 
+1
source

Source: https://habr.com/ru/post/976576/


All Articles