def get_param(self, name, required=False, store=None): """Return the value of a query string parameter as a string Args: name: Parameter name, case-sensitive (e.g., 'sort') required: Set to True to raise HTTPBadRequest instead of returning gracefully when the parameter is not found (default False) store: A dict-like object in which to place the value of the param, but only if the param is found. Returns: The value of the param as a string, or None if param is not found and is not required. Raises: HTTPBadRequest: The param was not found in the request, but was required. """ # PERF: Use if..in since it is a good all-around performer; we don't # know how likely params are to be specified by clients. if name in self._params: if store is not None: store[name] = self._params[name] return self._params[name] if not required: return None description = 'The "' + name + '" query parameter is required.' raise HTTPBadRequest('Missing query parameter', description)
def get_header(self, name, required=False): """Return a header value as a string Args: name: Header name, case-insensitive (e.g., 'Content-Type') required: Set to True to raise HttpBadRequest instead of returning gracefully when the header is not found (default False) Returns: The value of the specified header if it exists, or None if the header is not found and is not required. Raises: HTTPBadRequest: The header was not found in the request, but it was required. """ # Use try..except to optimize for the header existing in most cases try: # Don't take the time to cache beforehand, using HTTP naming. # This will be faster, assuming that most headers are looked # up only once, and not all headers will be requested. return self._headers[name.upper().replace('-', '_')] except KeyError: if not required: return None description = 'The "' + name + '" header is required.' raise HTTPBadRequest('Missing header', description)
def get_param_as_list(self, name, transform=None, required=False, store=None): """Return the value of a query string parameter as a list Note that list items must be comma-separated. Args: name: Parameter name, case-sensitive (e.g., 'limit') transform: An optional transform function that takes as input each element in the list as a string and outputs a transformed element for inclusion in the list that will be returned. required: Set to True to raise HTTPBadRequest instead of returning gracefully when the parameter is not found or is not an integer (default False) store: A dict-like object in which to place the value of the param, but only if the param is found (default None) Returns: The value of the param if it is found. Otherwise, returns None unless required is True. Raises HTTPBadRequest: The param was not found in the request, but was required. """ # PERF: Use if..in since it is a good all-around performer; we don't # know how likely params are to be specified by clients. if name in self._params: items = self._params[name].split(',') if transform is not None: try: items = [transform(x) for x in items] except ValueError: desc = ('The value of the "' + name + '" query parameter ' 'is not formatted correctly.') raise InvalidParamValueError(desc) if store is not None: store[name] = items return items if not required: return None raise HTTPBadRequest('Missing query parameter', 'The "' + name + '" query parameter is required.')
def get_param_as_bool(self, name, required=False, store=None): """Return the value of a query string parameter as a boolean The following bool-like strings are supported:: TRUE_STRINGS = ('true', 'True', 'yes') FALSE_STRINGS = ('false', 'False', 'no') Args: name (str): Parameter name, case-sensitive (e.g., 'limit') required (bool, optional): Set to True to raise HTTPBadRequest instead of returning gracefully when the parameter is not found or is not a recognized bool-ish string (default False). store (dict, optional): A dict-like object in which to place the value of the param, but only if the param is found (default *None*). Returns: bool: The value of the param if it is found and can be converted to a boolean. If the param is not found, returns *None* unless required is True. Raises HTTPBadRequest: The param was not found in the request, even though it was required to be there. """ params = self._params # PERF: Use if..in since it is a good all-around performer; we don't # know how likely params are to be specified by clients. if name in params: val = params[name] if val in TRUE_STRINGS: val = True elif val in FALSE_STRINGS: val = False else: msg = 'The value of the parameter must be "true" or "false".' raise InvalidParam(msg, name) if store is not None: store[name] = val return val if not required: return None description = 'The "' + name + '" query parameter is required.' raise HTTPBadRequest('Missing query parameter', description)
def get_param(self, name, required=False, store=None): """Return the value of a query string parameter as a string. Note: If an HTML form is POSTed to the API using the *application/x-www-form-urlencoded* media type, the parameters from the request body will be merged into the query string parameters. Args: name (str): Parameter name, case-sensitive (e.g., 'sort') required (bool, optional): Set to True to raise HTTPBadRequest instead of returning gracefully when the parameter is not found (default False) store (dict, optional): A dict-like object in which to place the value of the param, but only if the param is found. Returns: string: The value of the param as a string, or *None* if param is not found and is not required. Raises: HTTPBadRequest: The param was not found in the request, but was required. """ params = self._params # PERF: Use if..in since it is a good all-around performer; we don't # know how likely params are to be specified by clients. if name in params: if store is not None: store[name] = params[name] return params[name] if not required: return None description = 'The "' + name + '" query parameter is required.' raise HTTPBadRequest('Missing query parameter', description)
def get_param_as_int(self, name, required=False, min=None, max=None, store=None): """Return the value of a query string parameter as an int Args: name: Parameter name, case-sensitive (e.g., 'limit') required: Set to True to raise HTTPBadRequest instead of returning gracefully when the parameter is not found or is not an integer (default False) min: Set to the minimum value allowed for this param. If the param is found and it is less than min, an HTTPError is raised. max: Set to the maximum value allowed for this param. If the param is found and its value is greater than max, an HTTPError is raised. store: A dict-like object in which to place the value of the param, but only if the param is found (default None) Returns: The value of the param if it is found and can be converted to an integer. If the param is not found, returns None, unless required is True. Raises HTTPBadRequest: The param was not found in the request, even though it was required to be there. Also raised if the param's value falls outside the given interval, i.e., the value must be in the interval: min <= value <= max to avoid triggering an error. """ # PERF: Use if..in since it is a good all-around performer; we don't # know how likely params are to be specified by clients. if name in self._params: val = self._params[name] try: val = int(val) except ValueError: description = ('The value of the "' + name + '" query ' 'parameter must be an integer.') raise InvalidParamValueError(description) if min is not None and val < min: description = ('The value of the "' + name + '" query ' 'parameter must be at least %d') % min raise InvalidHeaderValueError(description) if max is not None and max < val: description = ('The value of the "' + name + '" query ' 'parameter may not exceed %d') % max raise InvalidHeaderValueError(description) if store is not None: store[name] = val return val if not required: return None description = 'The "' + name + '" query parameter is required.' raise HTTPBadRequest('Missing query parameter', description)
def get_param_as_list(self, name, transform=None, required=False, store=None): """Return the value of a query string parameter as a list. Note that list items must be comma-separated. Args: name (str): Parameter name, case-sensitive (e.g., 'limit') transform (callable, optional): An optional transform function that takes as input each element in the list as a string and outputs a transformed element for inclusion in the list that will be returned. For example, passing the int function will transform list items into numbers. required (bool, optional): Set to True to raise HTTPBadRequest instead of returning gracefully when the parameter is not found or is not an integer (default False) store (dict, optional): A dict-like object in which to place the value of the param, but only if the param is found (default *None*). Returns: list: The value of the param if it is found. Otherwise, returns *None* unless required is True. for partial lists, *None* will be returned as a placeholder. For example:: things=1,,3 would be returned as:: ['1', None, '3'] while this:: things=,,, would just be retured as:: [None, None, None, None] Raises HTTPBadRequest: The param was not found in the request, but was required. """ params = self._params # PERF: Use if..in since it is a good all-around performer; we don't # know how likely params are to be specified by clients. if name in params: items = params[name].split(',') # PERF(kgriffs): Use if-else rather than a DRY approach # that sets transform to a passthrough function; avoids # function calling overhead. if transform is None: items = [i if i != '' else None for i in items] else: try: items = [transform(i) if i != '' else None for i in items] except ValueError: msg = 'The value is not formatted correctly.' raise InvalidParam(msg, name) if store is not None: store[name] = items return items if not required: return None raise HTTPBadRequest('Missing query parameter', 'The "' + name + '" query parameter is required.')