Flask URL Routing - csrgxtu/Cocoa GitHub Wiki

How do flask routing urls?

URL routing is the component that connects the requests with view functions. when the web application receives a request, it first find the corresponding view functions, and then execute the function with the right parameters, then assemble the response and return.

Flask use app.url_map store the url mappings, as following code snippet shows:

class Flask(object):
  def __init__(self, package_name):
    self.view_functions = {}
    self.url_map = Map()

Registering the url route

In Flask use the following decoration function add the mappings from URL to view functions.

def route(self, rule, **options):
 def decorator(f):
   self.add_url_rule(rule, f.__name__, **options)
   self.view_functions[f.__name__] = f
 return decorator
@app.route('/')
def welcome():
  return 'welcome ya'

so when you write the upper application code, it actually registered a url into url_map and view_functions, now url_map and view_functions is something like this:

url_map('/', 'welcome', **options)

view_functions = {
  'welcome': welcome
}

Matching the url to view_functions

when a request comes to web application, first assign the url_map to request context.url_map, and then match the request url to its view functions, and then execute the functions, got the result and make a response and return to the wsgi server.

def wsgi_app(self, environ, start_response):
   with self.request_context(environ): #
     rv = self.preprocess_request()
     if rv is None:
         rv = self.dispatch_request() # match route and execute it
     response = self.make_response(rv)
     response = self.process_response(response)
     return response(environ, start_response)

def dispatch_request(self):
   try:
     endpoint, values = self.match_request()
     return self.view_functions[endpoint](**values)
how to match?
  • first, use url find the corresponding endpoint from url_map
  • second, use the endpoint find the corresponding view function in view_functions