util.py 5.7 KB

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