def get_route(self, method, path): # Returns the right route according to method/path s_path = path.split(b'/')[1:] root = s_path[0] for route in get_routes(): # Check that HTTP method and url root are matching. if not (route['http_method'] == self.http_method and route['root'] == root): continue p = 0 # Check each element in the path. for elt in s_path: try: if type(route['splitpath'][p]) not in (str, bytes): # Then this is a regular expression. res = route['splitpath'][p].match(elt.decode('utf-8')) if not res: break else: if route['splitpath'][p] != elt: break except IndexError: break p += 1 if p == len(s_path) == len(route['splitpath']): return route raise HTTPError(404, 'URL not found.')
def route_request(self, ): """ Main function in charge to route the incoming HTTP request to the right function. """ # Let's parse and prepare url, path, query etc.. url_parsed = urlparse(self.path, 'http') path = url_parsed.path splitpath = path.split('/') if len(splitpath) == 1: raise HTTPError(404, 'Not found.') root = splitpath[1] self.query = parse_qs(url_parsed.query) # Loop on each defined route in the API. for route in get_routes(): urlvars = [] is_that_route = True # Check that HTTP method and url root are matching. if route['http_method'] == self.http_method and \ route['root'] == root: pos = 0 # Check each element in the path. for elt in splitpath[1:]: try: if type(route['splitpath'][pos]) is not str: # Then this is a regular expression. res = route['splitpath'][pos].match(elt) if res is not None: # If the regexp matches, we want to get the value # and append it in urlvars. urlvars.append(unquote_plus(res.group(1))) else: is_that_route = False break else: if route['splitpath'][pos] != elt: is_that_route = False break except IndexError: is_that_route = False break pos += 1 if is_that_route: if self.http_method == 'POST': # TODO: raise an HTTP error if the content-length is too large. try: # Load POST content expecting it is in JSON format. self.post_json = json.loads( self.rfile.read( int(self.headers['Content-Length'])). decode('utf-8')) except Exception as e: raise HTTPError( 400, 'Invalid json format: %s.' % (str(e))) http_context = { 'headers': self.headers, 'query': self.query, 'post': self.post_json, 'urlvars': urlvars } # Call the right API function. response = getattr(sys.modules[route['module']], route['function'])(http_context, self.cmd_queue, self.config, self.sessions, self.commands) return (200, response) raise HTTPError(404, 'URL not found.')