Method of Constructing URL with url_for in python

  • 2021-07-26 08:29:59
  • OfStack

URL is constructed with url_for, which accepts the function name as the first parameter, and also accepts the named parameters of the variable part corresponding to the URL rule, and the unknown variable part is added to the end of URL as the query parameter.

There are two reasons for building URL instead of choosing to spell URL directly in your code:

1) When there are changes in the future, it is only necessary to modify URL once, instead of replacing it everywhere;

2) The URL build escapes the special characters and Unicode data,

These jobs don't need to be handled by ourselves.

Here's an example:


from flask import Flask,url_for

app = Flask(__name__)

@app.route('/example/1/')
def example(id):
 pass

with app.test_request_context():
 print url_for('example',id=1)
 print url_for('example',id=2,next='/')

#text_request_context Helps us generate the request context in interactive mode. 

Implementation results:


/example/1/?id=1
/example/1/?id=2&next=%2F

Related articles: