You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.7 KiB

  1. try:
  2. from collections.abc import Mapping
  3. except ImportError: # pragma: no cover
  4. # Python < 3.3
  5. from collections import Mapping # pragma: no cover
  6. def string_types():
  7. """ Taken from https://git.io/JIv5J """
  8. return str,
  9. def is_namedtuple(value):
  10. """ https://stackoverflow.com/a/2166841/1843746
  11. But modified to handle subclasses of namedtuples.
  12. Taken from https://git.io/JIsfY
  13. """
  14. if not isinstance(value, tuple):
  15. return False
  16. f = getattr(type(value), '_fields', None)
  17. if not isinstance(f, tuple):
  18. return False
  19. return all(type(n) == str for n in f)
  20. def iteritems(d, **kw):
  21. """ Override iteritems for support multiple versions python.
  22. Taken from https://git.io/JIvMi
  23. """
  24. return iter(d.items(**kw))
  25. def varmap(func, var, context=None, name=None):
  26. """ Executes ``func(key_name, value)`` on all values
  27. recurisively discovering dict and list scoped
  28. values. Taken from https://git.io/JIvMN
  29. """
  30. if context is None:
  31. context = {}
  32. objid = id(var)
  33. if objid in context:
  34. return func(name, '<...>')
  35. context[objid] = 1
  36. if isinstance(var, (list, tuple)) and not is_namedtuple(var):
  37. ret = [varmap(func, f, context, name) for f in var]
  38. else:
  39. ret = func(name, var)
  40. if isinstance(ret, Mapping):
  41. ret = dict((k, varmap(func, v, context, k))
  42. for k, v in iteritems(var))
  43. del context[objid]
  44. return ret
  45. def get_environ(environ):
  46. """ Returns our whitelisted environment variables.
  47. Taken from https://git.io/JIsf2
  48. """
  49. for key in ('REMOTE_ADDR', 'SERVER_NAME', 'SERVER_PORT'):
  50. if key in environ:
  51. yield key, environ[key]