Flask theoretical basis (a) view function and reverse function URL (url_for)

First, the view function

1.1 Basic usage of
trying function is app.route or bp.route (blueprint) decorator decorative function. This function implements the conversion of the URL path, i.e. routing function, for example, the following code defines the default url '/' and '/ index /' the request url.

@app.route('/')
@app.route('/index/')
def hello_world():
  return 'hello world'

 

Attempting to function can specify the http request method, parameter passing methods in route decorator

@app.route('/login/',methods=['GET','POST'])

 

1.2 pass parameters

Trying to match a specific function url request, often you need to pass a parameter, such as passing the current page number

app.route @ ( ' / article_list / <int: Page> / ' )
 DEF article_list (Page):
  return  " You see the Page% s " % Page 

# http://127.0.0.1:5000/article_list/3

 

As the incoming int parameter page, when the request url to automatically assign page 3;

Parameter Type view function support string, int, float, path, uuid, any 6 types of parameters converter, wherein the converter when the default string (default call by default).

@bp.route('/user/<username>')
@login_required
def user(username):
  user = User.query.filter_by(username=username).first_or_404()

 

As call the default string converter url content matching a string passed to the username variable.

path converter similar string, but the incoming file path delimiter '/'. uuid uuid converter accepts a string and a change is automatically python object.

any converter provides a map, so that a matching function can view two different paths.

@app.route('/<any(about, help, imprint, class, "foo,bar"):page_name>')
def detail(page_name):
    if page_name == 'about':
        return 'about page'
    else:
        ...

 

Multi-parameter matching, the following code to query search results page word.

@app.route('/<wrod>/<int:page>')
def search(word,page):
return []

 

1.3 custom converters

Flask provide converters can solve the vast majority of demand, but there is always a wonderful work needs to process, which requires a custom converter.
Custom converters requires the following three steps:

 1) realize their inheritance BaseConverter converter:

from werkzeug.routing Import BaseConverter
 class MapConverter (BaseConverter): 

    DEF to_python (Self, values):
         "" " 
        the url parameters we need to convert the data type of 
        A: B; C: D; 
        " "" 
        # as a string create a dictionary type data 
        KVS = values.split ( ' ; ' ) 
        RES = []
         for kV in KVS: 
            (K, V) = kv.split ( ' : ' ) 
            RES [K, V] 
        return RES 

    DEF to_url (Self, values):
         "" "
        The dictionary type data { 'a': 'b' , 'c': 'd'} is converted to A: B; C: D; 
        "" " 
        # BaseConverter.to_url url is encoded 
        RES = ' ; ' .join ([BaseConverter.to_url (Self, K + ' : ' + values [K]) for K in values.keys ()])
         return RES

 

As the need to achieve and to_url to_python two methods, a string representing the transition between the object and the python

 

2) Tell flask I need to add a converter:

app.url_map.converters['map'] = MapConverter

 

3) started

 

@app.route('/detail/<list:params>/')
def detail(params):
    print 'parmas:%s' % params
    return 'success for url'
    
with app.test_request_context():
    print 'detail函数的url是:%s' % flask.url_for('detail', params=[1, 2, 3])

 

Two, URL reverse function

Refers to converting the view function is a function of the specific url;

url_for(endpoint, **values)

 

The first parameter endpoint view function will be a string corresponding to the name, the second optional parameter, the parameters need to pass the url.
E.g:

@app.route('/')
def hello_world():
    print(url_for('my_list',page=1))
    return 'hello world'

@app.route('/list/<page>')
def my_list(page):
    return 'my_list'

 

The third line as the first parameter in an attempt to url_for my_list string function, a method of receiving the results of the final printed page parameter as follows:

/list/1

 

If url_for third line one more parameter count

print(url_for('my_list',page=1,count=2))

 

Print results

/list/1/?count = 2

 

Meanwhile url_for automatically handles special strings.

2.1, using the reverse function in the template

You can also use url_for for example in the template:

<a href="{{ url_for('login') }}">登录</a>

 

In html head often need to introduce some static files, this time url_for the endpoint incoming static, filename passed in relative path

<script src="{{ url_for('static', filename='js/index.js') }}"></script>

 

static catalog templates directory at the same level.

2.2, how to get full path URL


As url parameters are obtained relative path to the current application, url_for can get the absolute path to relative websites?
For example, our local website in http://127.0.0.1 visit, we think we can add _external = True parameter in url_for method acquiring a complete http://127.0.0.1/list/1

{{ url_for('reset_password', token=token, _external=True) }}

 

As a line of text in the password reset e-mail, when we send password reset message, you need to send an absolute path, you can add _external = True.

 

Guess you like

Origin www.cnblogs.com/fog2012/p/flask_basic_theory_endpoint_urlfor.html