Flask's routing

Flask relies on wsgi to implement wsgi modules: wsgiref, werkzeug, uwsgi

Instantiate a Flask object with parameters in it

app = Flask(__name__,template_folder='templates',static_url_path='/xxxxxx')

Two ways to add routes

 1. When the program is started for the first time, it is to match the url and the view one by one

   Server startup is to find out the relationship between url and view

   There are two ways to add routes in flask. According to the source code of the decorator, we generally use the first one. 

Routing method one:

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

   def index():
      return "Index"
Route 2:
  def order():
     return 'Order'

app.add_url_rule('/order',view_func=order)  

2. Regarding endpoints, it is equivalent to aliasing in Django

from flask import Flask,render_template,redirect,url_for

app = Flask( __name__ )    #Instantiate an object

'''
Implementation process
1.执行[email protected]('/index',methods=['GET','POST'])
2.@decorator
  新  index = decorator(index)
    The essence is to execute add_url_rule
    self.add_url_rule(rule, endpoint, f, **options)
''' 
#So there are two ways to create a route 
# endpoint='n1' is equivalent to the alias in our route in django, 
@app.route( ' /index ' ,methods=[ ' GET ' , ' POST ' ],endpoint= ' n1 ' ) #Call the route method and return a value 
 # Here you can see the source code of route, route returns a function 
def index():
    v1=url_for('n1')
    v2=url_for('n2')
    v3=url_for('n3')
    print(v1,v2,v3)
    return "index"

@app.route('/login',methods=['GET','POST'],endpoint='n2')
def login():
    return "login"

@app.route('/logout',methods=['GET','POST'],endpoint='n3')
def logout():
    return "logout"

#This is the second way to add routes, generally we use the first 
def   order():
     return  ' Order ' 
app.add_url_rule( ' /order ' ,view_func= order)

if __name__ == '__main__':
    app.run()

 

3. About the converter

 
from flask import Flask
from werkzeug.routing import BaseConverter

app = Flask(__name__)


class RegexConverter(BaseConverter):
    '''
    Custom URL matching regular expression
    '''
    def __init__(self,map,regex):
        super(RegexConverter,self).__init__(map)
        self.regex = regex
    def to_python(self, value):
        """
        When the route is matched, after the match is successful, the parameter passed to the view function gets the value
        :param value:
        :return:
        """
        return int(value)
    def to_url(self, value):
        """
        When using url_for to generate a URL in reverse, the passed parameters are processed by this method, and the returned value is used to generate the parameters in the URL
        :param value:
        :return:
        """ 
        val = super(RegexConverter, self).to_url(value) #Inherit     the parent class 
        return val
app.url_map.converters['xxx'] = RegexConverter
@app.route('/index/<xxx("\d+"):nid>',methods=['GET','POST'])

def index(nid): #This parameter means that a number can be filled in after index, and this number will be automatically filled in for the nid parameter 
    print (nid,type(nid))
     return  " index "

if __name__ == '__main__':
    app.run()
 

4. Directly transfer the path of the old function to the new function (redirect_to = '/index')

from flask import Flask

app = Flask(__name__)

@app.route('/index',methods=['GET','POST'],redirect_to='/index')
def index():
    return "老功能"

@app.route('/new',methods=['GET','POST'])
def new():
    return "新功能"

if __name__ == '__main__':
    app.run()
5. Decorator Jobs
from flask import Flask,render_template,redirect
import functools
app = Flask(__name__)


def wapper(func):
    @functools.wraps(func)
    def inner(*args,**kwargs):
        print('before')
        return func(*args,**kwargs)
    return inner

@app.route('/xxx',methods=['GET','POST'])
@wapper
def  index():
    return "index"

@app.route('/order',methods=['GET','POST'])
@wapper
def order():
    return "order"

if __name__ == '__main__':
    app.run()
 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325120912&siteId=291194637