flask route understanding
first let’s look at the example code of python flask web framework.
here we use the app.route to complish the route to ‘/’ and ‘/post/post_id’ here are map of url and it’s callback(function).
after we define the router, the hello function will be invoked when the user navigate to the ‘http://base_url/’ and show_post function will be invoked when user navigate to the ‘http://base_url/post/post_id’.
it’s not hard to conclude that the flask route just build an relation between the url and function.
the WSGI can be divided into there part according it’s function:
- server
- middleware
- application
the server listen to the port and get the request, after getting the request it will invoke the middleware, the middleware will let the application to deal with the request.
here is how WSGI deal with a http request:
-
server gets the request and form the environ and start_response, then invoke the middleware.
-
middleware will find the function according the environ formed by server, after that the middleware will invoke the application.
-
the application build the final response sent to user.
structure like this:
the code above create a middleware and its main function is delivering the request.
how can the middleware can deliver the request?
the main difficult is to build the relation between the request url and its function.
we first implement the Flask class myself:
this is a very simple flask middleware, here we include the function:
- meet the require of WSGI. can invoke the application.
- save the map of url and function.
- can find the function according to the url.
but the flask use the werkzeug lib to save the url and function information. it’s more complicated than we define.
In werkzeug lib, we use Rule to save the url, endpoint, function:
(url, endpoint, function)
here use two separate dictionary to save the Rule.
- {url: endpoint}
- {endpoint: function}
start the flask server
this code invoke the WSGI server inside the python standard lib. whatever the server is, the Flask.__call__ will be invoked finally. this function will accomplish the dispatch task.
conclusion
- the Flask class is WSGI’s dispatch middleware
- Flask’s url_map save all the (url, endpoint, function) relations
- Flask’s view_functions save all the {endpoint: function} relations
- dispatch request first find the endpoint according to the url, then use endpoint to find out the function.
happy coding.