flask_utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. This module defines utility functions related to the Flask framework.
  3. """
  4. import functools
  5. import random
  6. import re
  7. import string
  8. import flask
  9. import werkzeug.wrappers
  10. PATH_PARAMETER = re.compile(r'\{([^}]*)\}')
  11. # map Swagger type to flask path converter
  12. # see http://flask.pocoo.org/docs/0.10/api/#url-route-registrations
  13. PATH_PARAMETER_CONVERTERS = {
  14. 'integer': 'int',
  15. 'number': 'float',
  16. 'path': 'path'
  17. }
  18. def flaskify_endpoint(identifier, randomize=None):
  19. """
  20. Converts the provided identifier in a valid flask endpoint name
  21. :type identifier: str
  22. :param randomize: If specified, add this many random characters (upper case
  23. and digits) to the endpoint name, separated by a pipe character.
  24. :type randomize: int | None
  25. :rtype: str
  26. """
  27. result = identifier.replace('.', '_')
  28. if randomize is None:
  29. return result
  30. chars = string.ascii_uppercase + string.digits
  31. return "{result}|{random_string}".format(
  32. result=result,
  33. random_string=''.join(random.SystemRandom().choice(chars) for _ in range(randomize)))
  34. def convert_path_parameter(match, types):
  35. name = match.group(1)
  36. swagger_type = types.get(name)
  37. converter = PATH_PARAMETER_CONVERTERS.get(swagger_type)
  38. return '<{}{}{}>'.format(
  39. converter or '', ':' if converter else '', name.replace('-', '_')
  40. )
  41. def flaskify_path(swagger_path, types=None):
  42. """
  43. Convert swagger path templates to flask path templates
  44. :type swagger_path: str
  45. :type types: dict
  46. :rtype: str
  47. >>> flaskify_path('/foo-bar/{my-param}')
  48. '/foo-bar/<my_param>'
  49. >>> flaskify_path('/foo/{someint}', {'someint': 'int'})
  50. '/foo/<int:someint>'
  51. """
  52. if types is None:
  53. types = {}
  54. convert_match = functools.partial(convert_path_parameter, types=types)
  55. return PATH_PARAMETER.sub(convert_match, swagger_path)
  56. def is_flask_response(obj: object) -> bool:
  57. """
  58. Verifies if obj is a default Flask response instance.
  59. >>> is_flask_response(redirect('http://example.com/'))
  60. True
  61. >>> is_flask_response(flask.Response())
  62. True
  63. """
  64. return isinstance(obj, flask.Response) or isinstance(obj, werkzeug.wrappers.Response)