filter_form

privex.helpers.common.filter_form(form: Mapping, *keys, cast: callable = None) → Dict[str, Any][source]

Extract the keys keys from the dict-like form if they exist and return a dictionary containing the keys and values found.

Optionally, if cast isn’t None, then cast will be called to cast each form value to the desired type, e.g. int, Decimal, or str.

Example usage:

>>> a = dict(a=1, c=2, d=3)
>>> filter_form(a, 'a', 'c', 'e')
{'a': 1, 'c': 2}
>>> b = dict(lorem=1, ipsum='2', dolor=5.67)
>>> filter_form(b, 'lorem', 'ipsum', 'dolor', cast=int)
{'lorem': 1, 'ipsum': 2, 'dolor': 5}
Parameters
  • form (Mapping) – A dict-like object to extract key from.

  • keys (str|Any) – One or more keys to extract from form

  • cast (callable) – Cast the value of any extract form key using this callable

Return dict filtered_form

A dict containing the extracted keys and respective values from form