util.py 5.4 KB

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