util.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. """Miscellaneous WSGI-related Utilities"""
  2. import posixpath
  3. __all__ = [
  4. 'FileWrapper', 'guess_scheme', 'application_uri', 'request_uri',
  5. 'shift_path_info', 'setup_testing_defaults',
  6. ]
  7. class FileWrapper:
  8. """Wrapper to convert file-like objects to iterables"""
  9. def __init__(self, filelike, blksize=8192):
  10. self.filelike = filelike
  11. self.blksize = blksize
  12. if hasattr(filelike,'close'):
  13. self.close = filelike.close
  14. def __iter__(self):
  15. return self
  16. def __next__(self):
  17. data = self.filelike.read(self.blksize)
  18. if data:
  19. return data
  20. raise StopIteration
  21. def guess_scheme(environ):
  22. """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'
  23. """
  24. if environ.get("HTTPS") in ('yes','on','1'):
  25. return 'https'
  26. else:
  27. return 'http'
  28. def application_uri(environ):
  29. """Return the application's base URI (no PATH_INFO or QUERY_STRING)"""
  30. url = environ['wsgi.url_scheme']+'://'
  31. from urllib.parse import quote
  32. if environ.get('HTTP_HOST'):
  33. url += environ['HTTP_HOST']
  34. else:
  35. url += environ['SERVER_NAME']
  36. if environ['wsgi.url_scheme'] == 'https':
  37. if environ['SERVER_PORT'] != '443':
  38. url += ':' + environ['SERVER_PORT']
  39. else:
  40. if environ['SERVER_PORT'] != '80':
  41. url += ':' + environ['SERVER_PORT']
  42. url += quote(environ.get('SCRIPT_NAME') or '/', encoding='latin1')
  43. return url
  44. def request_uri(environ, include_query=True):
  45. """Return the full request URI, optionally including the query string"""
  46. url = application_uri(environ)
  47. from urllib.parse import quote
  48. path_info = quote(environ.get('PATH_INFO',''), safe='/;=,', encoding='latin1')
  49. if not environ.get('SCRIPT_NAME'):
  50. url += path_info[1:]
  51. else:
  52. url += path_info
  53. if include_query and environ.get('QUERY_STRING'):
  54. url += '?' + environ['QUERY_STRING']
  55. return url
  56. def shift_path_info(environ):
  57. """Shift a name from PATH_INFO to SCRIPT_NAME, returning it
  58. If there are no remaining path segments in PATH_INFO, return None.
  59. Note: 'environ' is modified in-place; use a copy if you need to keep
  60. the original PATH_INFO or SCRIPT_NAME.
  61. Note: when PATH_INFO is just a '/', this returns '' and appends a trailing
  62. '/' to SCRIPT_NAME, even though empty path segments are normally ignored,
  63. and SCRIPT_NAME doesn't normally end in a '/'. This is intentional
  64. behavior, to ensure that an application can tell the difference between
  65. '/x' and '/x/' when traversing to objects.
  66. """
  67. path_info = environ.get('PATH_INFO','')
  68. if not path_info:
  69. return None
  70. path_parts = path_info.split('/')
  71. path_parts[1:-1] = [p for p in path_parts[1:-1] if p and p != '.']
  72. name = path_parts[1]
  73. del path_parts[1]
  74. script_name = environ.get('SCRIPT_NAME','')
  75. script_name = posixpath.normpath(script_name+'/'+name)
  76. if script_name.endswith('/'):
  77. script_name = script_name[:-1]
  78. if not name and not script_name.endswith('/'):
  79. script_name += '/'
  80. environ['SCRIPT_NAME'] = script_name
  81. environ['PATH_INFO'] = '/'.join(path_parts)
  82. # Special case: '/.' on PATH_INFO doesn't get stripped,
  83. # because we don't strip the last element of PATH_INFO
  84. # if there's only one path part left. Instead of fixing this
  85. # above, we fix it here so that PATH_INFO gets normalized to
  86. # an empty string in the environ.
  87. if name=='.':
  88. name = None
  89. return name
  90. def setup_testing_defaults(environ):
  91. """Update 'environ' with trivial defaults for testing purposes
  92. This adds various parameters required for WSGI, including HTTP_HOST,
  93. SERVER_NAME, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO,
  94. and all of the wsgi.* variables. It only supplies default values,
  95. and does not replace any existing settings for these variables.
  96. This routine is intended to make it easier for unit tests of WSGI
  97. servers and applications to set up dummy environments. It should *not*
  98. be used by actual WSGI servers or applications, since the data is fake!
  99. """
  100. environ.setdefault('SERVER_NAME','127.0.0.1')
  101. environ.setdefault('SERVER_PROTOCOL','HTTP/1.0')
  102. environ.setdefault('HTTP_HOST',environ['SERVER_NAME'])
  103. environ.setdefault('REQUEST_METHOD','GET')
  104. if 'SCRIPT_NAME' not in environ and 'PATH_INFO' not in environ:
  105. environ.setdefault('SCRIPT_NAME','')
  106. environ.setdefault('PATH_INFO','/')
  107. environ.setdefault('wsgi.version', (1,0))
  108. environ.setdefault('wsgi.run_once', 0)
  109. environ.setdefault('wsgi.multithread', 0)
  110. environ.setdefault('wsgi.multiprocess', 0)
  111. from io import StringIO, BytesIO
  112. environ.setdefault('wsgi.input', BytesIO())
  113. environ.setdefault('wsgi.errors', StringIO())
  114. environ.setdefault('wsgi.url_scheme',guess_scheme(environ))
  115. if environ['wsgi.url_scheme']=='http':
  116. environ.setdefault('SERVER_PORT', '80')
  117. elif environ['wsgi.url_scheme']=='https':
  118. environ.setdefault('SERVER_PORT', '443')
  119. _hoppish = {
  120. 'connection', 'keep-alive', 'proxy-authenticate',
  121. 'proxy-authorization', 'te', 'trailers', 'transfer-encoding',
  122. 'upgrade'
  123. }.__contains__
  124. def is_hop_by_hop(header_name):
  125. """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header"""
  126. return _hoppish(header_name.lower())