Flask learning route

One. The basic definition of the route

# Specify the access path to demo1

@app.route('/demo1')

def demo1():

    return 'demo1'

two. Common routing arrangement

@ app.route ( '/ user / < username>') # usual default when no parameter is a string

@ app.route ( '/ post / < int: post_id>') # common    # specified int , integer instructions are

@app.route('/post/<float:post_id>')

@app.route('/post/<path:path>')

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

three. Routing transmission parameters can be set , two ways

1. one for the delivery route parameter [ not limited Type ]

2. Routing transfer parameters [ defined data type ]

The following is an example corresponding:

# ! / Usr / bin / env Python 
# - * - Coding: UTF-8 - * - 
__author__ = " HSZ " 

from the Flask Import the Flask 

App = the Flask ( __name__ ) 


# load the project configuration 
# Configure class 
class Config (Object): 
    DEBUG = True 


app.config.from_object (Config) 


# route passing parameters [not limited type] 
@ app.route ( ' / User / <user_id> ' )
 DEF user_info_1 (user_id):
     return  ' Hello info_1 S% ' % user_id 


#Passing route parameter [data type defined], with a Liezi int type, may be selected bool, float can be a 
# user_id must be an integer 
@ app.route ( ' / User / <int: user_id> ' )
 DEF user_info_2 (user_id) :
     return  ' Hello INFO_2 D% ' % user_id 


IF  the __name__ == ' __main__ ' : 
    app.run (Host = ' 127.0.0.1 ' , Port = 9000 )
     "" " 
    test Description: 
        test. 1: 
        of http://127.0.0.1 : 9000 / user / qwer 
        this situation is a function of accessing a url, as qwerb is not an integer, it is not limited to the type of the route  
        test 2:
        http://127.0.0.1:9000/user/2 
        this case will choose the type of route defined 
        Test 3: 
        Notes defined, so that after use the following test url: 
        http://127.0.0.1:9000/user/ 2 
        this will take indefinite routing 
"" "

four. Routing of url_for () function

1. to construct the function specified URL

# Example. 1: 
# ! / Usr / bin / Python the env 
# - * - Coding: UTF-. 8 - * - 
__author__ = " HSZ " 

from Flask Import the Flask, the url_for
 from Flask Import the redirect 

App = the Flask ( the __name__ ) 


@ app.route ( ' / index ' )   # Endpoint alias 
DEF Home ():
     "" " 
    the url_for is a function to accept view function name (string) as a parameter and returns view corresponding function url 
    acquires url distal inputted through url_for home is What 
    : return: 
    "" " 
    v = url_for ( " Home" )
     Print (V)
     return  " index " 

# the url_for () using endpoint, URL path constructed by a reverse mechanism  
@ app.route ( ' / index / <int: NID> ' , Endpoint = " AAA " )   # Endpoint alias 
DEF zzz (NID):
     "" " 
    here used an alias, the alias function zzz aaa 
    so on are url_for aaa 
    : param NID: 
    : return: 
    " "" 
    V = url_for ( " aaa " , NID = NID)
     Print (v)
     return  "index2"


if __name__ == '__main__':
app.run(host='127.0.0.1', port=9000)

2. Access static files (CSS / JavaScript , etc. )

As long as you create a directory where the package or module called  file static folder, use in applications / static can access.

url_for('static', filename='style.css')

This file should be stored on the file system static / style.css

Fives. Routing regular match mode

1. The custom converter implemented

In web development, may appear to limit user access rules scenes, then this time you need to use the regular match, according to its own rules to define the parameters and then request access

Specific implementation steps of:

(1) introduced into the converter base class: in Flask , all the matching rules are routing object recording a converter

(2) custom converters: custom class inherited from the base class converter

(3) is added to the default converter converter dictionaries

(4) using a custom converter to implement a custom matching rules

 

# ! / Usr / bin / the env Python 
# - * - Coding: UTF-. 8 - * - 
__author__ = " HSZ " 

# below write a custom routing switches 

from Flask Import the Flask 

App = the Flask ( the __name__ ) 

# import converter yl class 
from werkzeug.routing Import BaseConverter 


class MobileNumberConverter (BaseConverter):
     "" " 
    phone number custom routing switches 
    " "" 
    REGEX = " \ D {}. 11 " 


# Add converter to converter default dictionary, and assign the converter is used to name: Mobile 
app.url_map.converters [ ' Mobile' ] = MobileNumberConverter 


# used to implement a custom converter matching rules 
@ app.route (R & lt " / SMS / <Mobile: mobile_number> / " )   # mobile_number telephone number is tested 
DEF SMS (mobile_number):
     "" " 
    by url visit: 
    http://127.0.0.1:9000/sms/13666666666/ 
    : param mobile_number: 
    : return: 
    "" " 
    Print (mobile_number)
     return  " phone number via SMS " 


# Example 2 
class RegexConverter (BaseConverter):
     " " " I am routing switches " ""

    def __init__(self, url_map, *args):
         # Super () .__ the init __ (url_map) or write # 
        # url_map all url a tuple 
        . Super (RegexConverter, Self) the __init__ (url_map)   # initialization classification 
        self.regex = args [0]   # is a meta group 


app.url_map.converters [ ' REG ' ] = RegexConverter 


# \ W capital letter lowercase underlined 
@ app.route (R & lt " / Register / <REG ( '\ {W}. 4, 6'): username> / " )
 DEF REG (username):   # this function name is no limit 
    . "" " 
    the following url accessed via: 
    http://127.0.0.1:9000/register/qwer/  
    : param username:
    : return: 
    " ""
    print(username)
    return "ok reg"


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=9000)

 

2. The system comes converter

In werkzeug.routing.py source file

 

DEFAULT_CONVERTERS = {
    "default": UnicodeConverter,
    "string": UnicodeConverter,
    "any": AnyConverter,
    "path": PathConverter,
    "int": IntegerConverter,
    "float": FloatConverter,
    "uuid": UUIDConverter,
}

 

The system comes with all the above types.

The system comes with the converter using specific methods are written in the comments in the code for each converter, please pay attention to each converter initialization parameters.

Guess you like

Origin www.cnblogs.com/hszstudypy/p/12182201.html