1. Route parameters

What is a route?

  • Is a binding application and THE CORRESPONDING mapping of URL address; When editing a project, the class that usually performs a function is a routing class, or routing for short
  • The names of routes and views must be globally unique. Otherwise, an error occurs.

There are two transmission and classification modes of routes:

1 Do not specify type transfer route parameters

from flask import Flask
app = Flask(__name__)

Pass route parameters without specifying type
@app.route("/collection/<collection_id>/<aritcle_id>")
def index(collection_id,aritcle_id) :
    return f"collection_id={collection_id}, aritcle_id={aritcle_id}"

Load the project configuration
class Config(object) :
    DEBUG = True

app.config.from_object(Config)

if __name__ == '__main__':
    Flask all routes are registered in urL_map.
    print( app.url_map )
    app.run(host="0.0.0.0",port=5000)
Copy the code

2 Specify the type of route parameters to be transmitted

from flask import Flask

app = Flask(__name__)

# Define the type of route parameter to pass
All flask built-in routing converters are configured by the DEFAULT_CONVERTERS dictionary of Werkzeug. routing.
All the routing converters in # Flask are essentially routable for matching parameter values. All routing converters must directly or indirectly inherit from the BaseConverter routing converter base class

@app.route("/sms/<int(min=10,max=100):mobile>")
def sms(mobile) :
    return f"mobile={mobile}"

Load the project configuration
class Config(object) :
    DEBUG = True

app.config.from_object(Config)

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

Copy the code

Flask system’s built-in converter is written in the file werkzeug.routing.py. The following dictionary can be seen at the bottom:

DEFAULT_CONVERTERS = {
  "default": UnicodeConverter,
  "string": UnicodeConverter,
  "any": AnyConverter,
  "path": PathConverter,
  "int": IntegerConverter,
  "float": FloatConverter,
  "uuid": UUIDConverter, # accept UUID (universal unique identifier) string xxxx-XXXX-xxXXX-xxxxx
}
Copy the code

Custom routing converter

Implementation steps

  1. Import the converter base class. In Flask, all routing rules are implemented through converter objects
  2. Custom converter: The parent class is BaseConverter
  3. Add converters to the default conversion dictionary
  4. Implement custom matching conversion rules using custom converters
from flask import Flask

app = Flask(__name__)

# Custom routing converter
from werkzeug.routing import BaseConverter

class RegexConverter(BaseConverter) :
    def __init__(self,map,*args) :
        super().__init__(map)
        # regular parameter
        self.regex = args[0]

Add the custom converter to the converter dictionary and specify the name of the converter to use: re
app.url_map.converters['re'] = RegexConverter

# rematch routes
@app.route("/sms/<re('1[3-9]\d{9}'):mobile>")
def sms(mobile) :
    return f"mobile={mobile}"

Load the project configuration
class Config(object) :
    DEBUG = True

app.config.from_object(Config)

if __name__ == '__main__':
    Flask all routes are registered in urL_map.
    print( app.url_map )
    app.run(host="0.0.0.0",port=5000)
    
Copy the code
from werkzeug.routing import BaseConverter
 
class MobileConverter(BaseConverter) :
    "" Mobile number Type restriction ""
    def __init__(self,map,*args) :
        super().__init__(map)
        self.regex = "1[3-9]\d{9}"
Add custom converters to flask's default converter dictionary, alongside the old int,float, etc
app.url_map.converters['mob'] = MobileConverter # dictionary oh

# Same as the original route parameter restriction, call the custom converter name
@app.route(rule='/user/<mob:mobile>')
def user(mobile) :
    return mobile
Copy the code
# 1. Import flask's routing converter
from werkzeug.routing import BaseConverter
# 2. Create a custom routing converter
class RegexConverter(BaseConverter) :
    """ Parameter restriction based on re ""
    def __init__(self,map,*args) :
        super().__init__(map)
        self.regex = args[0]
# 3. Add custom converters to flask's default converter dictionary, alongside the old int,float, etc
app.url_map.converters['re'] = RegexConverter

# 4. Just like the original route parameter restriction, call the custom converter name
@app.route(rule='/user/<re("\w+@\w+\.\w+"):email>')
def user2(email) :
    print(app.url_map) Get a list of all routes
    return email

Declare and load the configuration
class Config() :
    DEBUG = True
app.config.from_object(Config)

if __name__ == '__main__':
    # run flask
    app.run(host="0.0.0.0")
Copy the code

Restrict HTTP requests

methods=[“post”,”put”,”get”,”delete”,”patch”]

from flask import Flask,request
app = Flask(__name__)
# from flask.app import Request
@app.route("/", methods=["POST"])
def index() :
    print("request.method=%s" % request.method)
    print("request.url=%s" % request.url)
    print("request.query_string=%s" % request.query_string)
    print("request.path=%s" % request.path)
    return  request.method

Load the project configuration
class Config(object) : 
    DEBUG = True

app.config.from_object(Config)

if __name__ == '__main__':
    Flask all routes are registered in urL_map.
    print( app.url_map )
    app.run(host="0.0.0.0",port=5000)

Copy the code

Results:

Gets the parsed query string

from flask import Flask,request
from urllib.parse import parse_qs

from werkzeug.datastructures import ImmutableMultiDict

app = Flask(__name__)

@app.route("/", methods=["POST"])
def index() :
    """ Get the query string """
    Get the native query string query_string
    # print( request.query_string )
    # print( parse_qs( request.query_string.decode() ) )
    "" "POST 127.0.0.1:5000? username=xiaoming&pwd=123 b'username=xiaoming&pwd=123' {'username': ['xiaoming'], 'pwd': ['123']} """
    Get the parsed query string
    # print(request.args)
    # print(request.args.get("username"))
    # print(request.args.get("lve"))
    # print(request.args.getlist("lve"))
    """POST /? username=xiaoming&pwd=123&lve=shoping&lve=game ImmutableMultiDict([('username', 'xiaoming'), ('pwd', From collections import OrderedDict xiaoming shoping ['shoping', 'game'] ""
    print(request.args.to_dict(flat=True))
    print(request.args.to_dict(flat=False))
    print(request.args)
    "" "POST 127.0.0.1:5000? username=xiaoming&pwd=123&lve=shoping&lve=game {'username': 'xiaoming', 'pwd': '123', 'lve': 'shoping'} {'username': ['xiaoming'], 'pwd': ['123'], 'lve': ['shoping', 'game']} """
    return "hello"

@app.route(rule="/data",methods=["post"."put"."patch"])
def data() :
    "" "accept the client to send over the original request body data, is the request json, request the form, the request, can not accept the data such as files, all will be kept here "" "
    print(request.data)
    return "hello"

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=5000,debug=True)
Copy the code