def __call__(self, request): # Get the dispatchers for the request method. dispatchers = self.request_dispatchers.get(request.method) # No dispatchers for method, send 405 with list of allowed methods. if dispatchers is None: return http.method_not_allowed(", ".join(self.request_dispatchers)) # Look up the best dispatcher dispatcher = _best_dispatcher(dispatchers, request) if dispatcher is not None: (callable, match) = dispatcher response = callable(self, request) # Try to autocomplete the content-type header if not set # explicitly. # If there's no accept from the client and there's only one # possible type from the match then use that as the best match. # Otherwise use mimeparse to work out what the best match was. If # the best match if not a wildcard then we know what content-type # should be. if isinstance(response, http.Response) and not response.headers.get("content-type"): accept = str(request.accept) if not accept and len(match["accept"]) == 1: best_match = match["accept"][0] else: best_match = mimeparse.best_match(match["accept"], accept) if "*" not in best_match: response.headers["content-type"] = best_match return response # No match, send 406 return http.not_acceptable([("Content-Type", "text/plain")], "406 Not Acceptable")
def _filter_dispatchers_on_accept(dispatchers, request): # Build an ordered list of the supported types. supported = [] for d in dispatchers: supported.extend(d[1]["accept"]) # Find the best accept type best_match = mimeparse.best_match(supported, str(request.accept)) # Return the matching dispatchers return [d for d in dispatchers if best_match in d[1]["accept"]]
def _filter_dispatchers_on_content_type(dispatchers, request): # Build an ordered list of the supported types. supported = [] for d in dispatchers: supported.extend(d[1]["content_type"]) # Find the best type. best_match = mimeparse.best_match(supported, str(request.headers["content-type"])) # Return the matching dispatchers return [d for d in dispatchers if best_match in d[1]["content_type"]]