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.

107 lines
3.4 KiB

4 years ago
  1. import re
  2. from aiohttp.web_exceptions import HTTPMovedPermanently
  3. from aiohttp.web_urldispatcher import SystemRoute
  4. __all__ = (
  5. 'middleware',
  6. 'normalize_path_middleware',
  7. )
  8. async def _check_request_resolves(request, path):
  9. alt_request = request.clone(rel_url=path)
  10. match_info = await request.app.router.resolve(alt_request)
  11. alt_request._match_info = match_info
  12. if not isinstance(match_info.route, SystemRoute):
  13. return True, alt_request
  14. return False, request
  15. def middleware(f):
  16. f.__middleware_version__ = 1
  17. return f
  18. def normalize_path_middleware(
  19. *, append_slash=True, remove_slash=False,
  20. merge_slashes=True, redirect_class=HTTPMovedPermanently):
  21. """
  22. Middleware factory which produces a middleware that normalizes
  23. the path of a request. By normalizing it means:
  24. - Add or remove a trailing slash to the path.
  25. - Double slashes are replaced by one.
  26. The middleware returns as soon as it finds a path that resolves
  27. correctly. The order if both merge and append/remove are enabled is
  28. 1) merge slashes
  29. 2) append/remove slash
  30. 3) both merge slashes and append/remove slash.
  31. If the path resolves with at least one of those conditions, it will
  32. redirect to the new path.
  33. Only one of `append_slash` and `remove_slash` can be enabled. If both
  34. are `True` the factory will raise an assertion error
  35. If `append_slash` is `True` the middleware will append a slash when
  36. needed. If a resource is defined with trailing slash and the request
  37. comes without it, it will append it automatically.
  38. If `remove_slash` is `True`, `append_slash` must be `False`. When enabled
  39. the middleware will remove trailing slashes and redirect if the resource
  40. is defined
  41. If merge_slashes is True, merge multiple consecutive slashes in the
  42. path into one.
  43. """
  44. correct_configuration = not (append_slash and remove_slash)
  45. assert correct_configuration, "Cannot both remove and append slash"
  46. @middleware
  47. async def impl(request, handler):
  48. if isinstance(request.match_info.route, SystemRoute):
  49. paths_to_check = []
  50. if '?' in request.raw_path:
  51. path, query = request.raw_path.split('?', 1)
  52. query = '?' + query
  53. else:
  54. query = ''
  55. path = request.raw_path
  56. if merge_slashes:
  57. paths_to_check.append(re.sub('//+', '/', path))
  58. if append_slash and not request.path.endswith('/'):
  59. paths_to_check.append(path + '/')
  60. if remove_slash and request.path.endswith('/'):
  61. paths_to_check.append(path[:-1])
  62. if merge_slashes and append_slash:
  63. paths_to_check.append(
  64. re.sub('//+', '/', path + '/'))
  65. if merge_slashes and remove_slash:
  66. merged_slashes = re.sub('//+', '/', path)
  67. paths_to_check.append(merged_slashes[:-1])
  68. for path in paths_to_check:
  69. resolves, request = await _check_request_resolves(
  70. request, path)
  71. if resolves:
  72. raise redirect_class(request.raw_path)
  73. return await handler(request)
  74. return impl
  75. def _fix_request_current_app(app):
  76. @middleware
  77. async def impl(request, handler):
  78. with request.match_info.set_current_app(app):
  79. return await handler(request)
  80. return impl