Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

wsgi.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. An implementation of
  5. U{Python Web Server Gateway Interface v1.0.1<http://www.python.org/dev/peps/pep-3333/>}.
  6. """
  7. from collections.abc import Sequence
  8. from sys import exc_info
  9. from warnings import warn
  10. from zope.interface import implementer
  11. from twisted.internet.threads import blockingCallFromThread
  12. from twisted.logger import Logger
  13. from twisted.python.failure import Failure
  14. from twisted.web.http import INTERNAL_SERVER_ERROR
  15. from twisted.web.resource import IResource
  16. from twisted.web.server import NOT_DONE_YET
  17. # PEP-3333 -- which has superseded PEP-333 -- states that, in both Python 2
  18. # and Python 3, text strings MUST be represented using the platform's native
  19. # string type, limited to characters defined in ISO-8859-1. Byte strings are
  20. # used only for values read from wsgi.input, passed to write() or yielded by
  21. # the application.
  22. #
  23. # Put another way:
  24. #
  25. # - In Python 2, all text strings and binary data are of type str/bytes and
  26. # NEVER of type unicode. Whether the strings contain binary data or
  27. # ISO-8859-1 text depends on context.
  28. #
  29. # - In Python 3, all text strings are of type str, and all binary data are of
  30. # type bytes. Text MUST always be limited to that which can be encoded as
  31. # ISO-8859-1, U+0000 to U+00FF inclusive.
  32. #
  33. # The following pair of functions -- _wsgiString() and _wsgiStringToBytes() --
  34. # are used to make Twisted's WSGI support compliant with the standard.
  35. if str is bytes:
  36. def _wsgiString(string): # Python 2.
  37. """
  38. Convert C{string} to an ISO-8859-1 byte string, if it is not already.
  39. @type string: C{str}/C{bytes} or C{unicode}
  40. @rtype: C{str}/C{bytes}
  41. @raise UnicodeEncodeError: If C{string} contains non-ISO-8859-1 chars.
  42. """
  43. if isinstance(string, str):
  44. return string
  45. else:
  46. return string.encode("iso-8859-1")
  47. def _wsgiStringToBytes(string): # Python 2.
  48. """
  49. Return C{string} as is; a WSGI string is a byte string in Python 2.
  50. @type string: C{str}/C{bytes}
  51. @rtype: C{str}/C{bytes}
  52. """
  53. return string
  54. else:
  55. def _wsgiString(string): # Python 3.
  56. """
  57. Convert C{string} to a WSGI "bytes-as-unicode" string.
  58. If it's a byte string, decode as ISO-8859-1. If it's a Unicode string,
  59. round-trip it to bytes and back using ISO-8859-1 as the encoding.
  60. @type string: C{str} or C{bytes}
  61. @rtype: C{str}
  62. @raise UnicodeEncodeError: If C{string} contains non-ISO-8859-1 chars.
  63. """
  64. if isinstance(string, str):
  65. return string.encode("iso-8859-1").decode("iso-8859-1")
  66. else:
  67. return string.decode("iso-8859-1")
  68. def _wsgiStringToBytes(string): # Python 3.
  69. """
  70. Convert C{string} from a WSGI "bytes-as-unicode" string to an
  71. ISO-8859-1 byte string.
  72. @type string: C{str}
  73. @rtype: C{bytes}
  74. @raise UnicodeEncodeError: If C{string} contains non-ISO-8859-1 chars.
  75. """
  76. return string.encode("iso-8859-1")
  77. class _ErrorStream:
  78. """
  79. File-like object instances of which are used as the value for the
  80. C{'wsgi.errors'} key in the C{environ} dictionary passed to the application
  81. object.
  82. This simply passes writes on to L{logging<twisted.logger>} system as
  83. error events from the C{'wsgi'} system. In the future, it may be desirable
  84. to expose more information in the events it logs, such as the application
  85. object which generated the message.
  86. """
  87. _log = Logger()
  88. def write(self, data):
  89. """
  90. Generate an event for the logging system with the given bytes as the
  91. message.
  92. This is called in a WSGI application thread, not the I/O thread.
  93. @type data: str
  94. @raise TypeError: On Python 3, if C{data} is not a native string. On
  95. Python 2 a warning will be issued.
  96. """
  97. if not isinstance(data, str):
  98. if str is bytes:
  99. warn(
  100. "write() argument should be str, not %r (%s)"
  101. % (data, type(data).__name__),
  102. category=UnicodeWarning,
  103. )
  104. else:
  105. raise TypeError(
  106. "write() argument must be str, not %r (%s)"
  107. % (data, type(data).__name__)
  108. )
  109. # Note that in old style, message was a tuple. logger._legacy
  110. # will overwrite this value if it is not properly formatted here.
  111. self._log.error(data, system="wsgi", isError=True, message=(data,))
  112. def writelines(self, iovec):
  113. """
  114. Join the given lines and pass them to C{write} to be handled in the
  115. usual way.
  116. This is called in a WSGI application thread, not the I/O thread.
  117. @param iovec: A C{list} of C{'\\n'}-terminated C{str} which will be
  118. logged.
  119. @raise TypeError: On Python 3, if C{iovec} contains any non-native
  120. strings. On Python 2 a warning will be issued.
  121. """
  122. self.write("".join(iovec))
  123. def flush(self):
  124. """
  125. Nothing is buffered, so flushing does nothing. This method is required
  126. to exist by PEP 333, though.
  127. This is called in a WSGI application thread, not the I/O thread.
  128. """
  129. class _InputStream:
  130. """
  131. File-like object instances of which are used as the value for the
  132. C{'wsgi.input'} key in the C{environ} dictionary passed to the application
  133. object.
  134. This only exists to make the handling of C{readline(-1)} consistent across
  135. different possible underlying file-like object implementations. The other
  136. supported methods pass through directly to the wrapped object.
  137. """
  138. def __init__(self, input):
  139. """
  140. Initialize the instance.
  141. This is called in the I/O thread, not a WSGI application thread.
  142. """
  143. self._wrapped = input
  144. def read(self, size=None):
  145. """
  146. Pass through to the underlying C{read}.
  147. This is called in a WSGI application thread, not the I/O thread.
  148. """
  149. # Avoid passing None because cStringIO and file don't like it.
  150. if size is None:
  151. return self._wrapped.read()
  152. return self._wrapped.read(size)
  153. def readline(self, size=None):
  154. """
  155. Pass through to the underlying C{readline}, with a size of C{-1} replaced
  156. with a size of L{None}.
  157. This is called in a WSGI application thread, not the I/O thread.
  158. """
  159. # Check for -1 because StringIO doesn't handle it correctly. Check for
  160. # None because files and tempfiles don't accept that.
  161. if size == -1 or size is None:
  162. return self._wrapped.readline()
  163. return self._wrapped.readline(size)
  164. def readlines(self, size=None):
  165. """
  166. Pass through to the underlying C{readlines}.
  167. This is called in a WSGI application thread, not the I/O thread.
  168. """
  169. # Avoid passing None because cStringIO and file don't like it.
  170. if size is None:
  171. return self._wrapped.readlines()
  172. return self._wrapped.readlines(size)
  173. def __iter__(self):
  174. """
  175. Pass through to the underlying C{__iter__}.
  176. This is called in a WSGI application thread, not the I/O thread.
  177. """
  178. return iter(self._wrapped)
  179. class _WSGIResponse:
  180. """
  181. Helper for L{WSGIResource} which drives the WSGI application using a
  182. threadpool and hooks it up to the L{http.Request}.
  183. @ivar started: A L{bool} indicating whether or not the response status and
  184. headers have been written to the request yet. This may only be read or
  185. written in the WSGI application thread.
  186. @ivar reactor: An L{IReactorThreads} provider which is used to call methods
  187. on the request in the I/O thread.
  188. @ivar threadpool: A L{ThreadPool} which is used to call the WSGI
  189. application object in a non-I/O thread.
  190. @ivar application: The WSGI application object.
  191. @ivar request: The L{http.Request} upon which the WSGI environment is
  192. based and to which the application's output will be sent.
  193. @ivar environ: The WSGI environment L{dict}.
  194. @ivar status: The HTTP response status L{str} supplied to the WSGI
  195. I{start_response} callable by the application.
  196. @ivar headers: A list of HTTP response headers supplied to the WSGI
  197. I{start_response} callable by the application.
  198. @ivar _requestFinished: A flag which indicates whether it is possible to
  199. generate more response data or not. This is L{False} until
  200. L{http.Request.notifyFinish} tells us the request is done,
  201. then L{True}.
  202. """
  203. _requestFinished = False
  204. _log = Logger()
  205. def __init__(self, reactor, threadpool, application, request):
  206. self.started = False
  207. self.reactor = reactor
  208. self.threadpool = threadpool
  209. self.application = application
  210. self.request = request
  211. self.request.notifyFinish().addBoth(self._finished)
  212. if request.prepath:
  213. scriptName = b"/" + b"/".join(request.prepath)
  214. else:
  215. scriptName = b""
  216. if request.postpath:
  217. pathInfo = b"/" + b"/".join(request.postpath)
  218. else:
  219. pathInfo = b""
  220. parts = request.uri.split(b"?", 1)
  221. if len(parts) == 1:
  222. queryString = b""
  223. else:
  224. queryString = parts[1]
  225. # All keys and values need to be native strings, i.e. of type str in
  226. # *both* Python 2 and Python 3, so says PEP-3333.
  227. self.environ = {
  228. "REQUEST_METHOD": _wsgiString(request.method),
  229. "REMOTE_ADDR": _wsgiString(request.getClientAddress().host),
  230. "SCRIPT_NAME": _wsgiString(scriptName),
  231. "PATH_INFO": _wsgiString(pathInfo),
  232. "QUERY_STRING": _wsgiString(queryString),
  233. "CONTENT_TYPE": _wsgiString(request.getHeader(b"content-type") or ""),
  234. "CONTENT_LENGTH": _wsgiString(request.getHeader(b"content-length") or ""),
  235. "SERVER_NAME": _wsgiString(request.getRequestHostname()),
  236. "SERVER_PORT": _wsgiString(str(request.getHost().port)),
  237. "SERVER_PROTOCOL": _wsgiString(request.clientproto),
  238. }
  239. # The application object is entirely in control of response headers;
  240. # disable the default Content-Type value normally provided by
  241. # twisted.web.server.Request.
  242. self.request.defaultContentType = None
  243. for name, values in request.requestHeaders.getAllRawHeaders():
  244. name = "HTTP_" + _wsgiString(name).upper().replace("-", "_")
  245. # It might be preferable for http.HTTPChannel to clear out
  246. # newlines.
  247. self.environ[name] = ",".join(_wsgiString(v) for v in values).replace(
  248. "\n", " "
  249. )
  250. self.environ.update(
  251. {
  252. "wsgi.version": (1, 0),
  253. "wsgi.url_scheme": request.isSecure() and "https" or "http",
  254. "wsgi.run_once": False,
  255. "wsgi.multithread": True,
  256. "wsgi.multiprocess": False,
  257. "wsgi.errors": _ErrorStream(),
  258. # Attend: request.content was owned by the I/O thread up until
  259. # this point. By wrapping it and putting the result into the
  260. # environment dictionary, it is effectively being given to
  261. # another thread. This means that whatever it is, it has to be
  262. # safe to access it from two different threads. The access
  263. # *should* all be serialized (first the I/O thread writes to
  264. # it, then the WSGI thread reads from it, then the I/O thread
  265. # closes it). However, since the request is made available to
  266. # arbitrary application code during resource traversal, it's
  267. # possible that some other code might decide to use it in the
  268. # I/O thread concurrently with its use in the WSGI thread.
  269. # More likely than not, this will break. This seems like an
  270. # unlikely possibility to me, but if it is to be allowed,
  271. # something here needs to change. -exarkun
  272. "wsgi.input": _InputStream(request.content),
  273. }
  274. )
  275. def _finished(self, ignored):
  276. """
  277. Record the end of the response generation for the request being
  278. serviced.
  279. """
  280. self._requestFinished = True
  281. def startResponse(self, status, headers, excInfo=None):
  282. """
  283. The WSGI I{start_response} callable. The given values are saved until
  284. they are needed to generate the response.
  285. This will be called in a non-I/O thread.
  286. """
  287. if self.started and excInfo is not None:
  288. raise excInfo[1].with_traceback(excInfo[2])
  289. # PEP-3333 mandates that status should be a native string. In practice
  290. # this is mandated by Twisted's HTTP implementation too, so we enforce
  291. # on both Python 2 and Python 3.
  292. if not isinstance(status, str):
  293. raise TypeError(
  294. "status must be str, not {!r} ({})".format(
  295. status, type(status).__name__
  296. )
  297. )
  298. # PEP-3333 mandates that headers should be a plain list, but in
  299. # practice we work with any sequence type and only warn when it's not
  300. # a plain list.
  301. if isinstance(headers, list):
  302. pass # This is okay.
  303. elif isinstance(headers, Sequence):
  304. warn(
  305. "headers should be a list, not %r (%s)"
  306. % (headers, type(headers).__name__),
  307. category=RuntimeWarning,
  308. )
  309. else:
  310. raise TypeError(
  311. "headers must be a list, not %r (%s)"
  312. % (headers, type(headers).__name__)
  313. )
  314. # PEP-3333 mandates that each header should be a (str, str) tuple, but
  315. # in practice we work with any sequence type and only warn when it's
  316. # not a plain list.
  317. for header in headers:
  318. if isinstance(header, tuple):
  319. pass # This is okay.
  320. elif isinstance(header, Sequence):
  321. warn(
  322. "header should be a (str, str) tuple, not %r (%s)"
  323. % (header, type(header).__name__),
  324. category=RuntimeWarning,
  325. )
  326. else:
  327. raise TypeError(
  328. "header must be a (str, str) tuple, not %r (%s)"
  329. % (header, type(header).__name__)
  330. )
  331. # However, the sequence MUST contain only 2 elements.
  332. if len(header) != 2:
  333. raise TypeError(f"header must be a (str, str) tuple, not {header!r}")
  334. # Both elements MUST be native strings. Non-native strings will be
  335. # rejected by the underlying HTTP machinery in any case, but we
  336. # reject them here in order to provide a more informative error.
  337. for elem in header:
  338. if not isinstance(elem, str):
  339. raise TypeError(f"header must be (str, str) tuple, not {header!r}")
  340. self.status = status
  341. self.headers = headers
  342. return self.write
  343. def write(self, data):
  344. """
  345. The WSGI I{write} callable returned by the I{start_response} callable.
  346. The given bytes will be written to the response body, possibly flushing
  347. the status and headers first.
  348. This will be called in a non-I/O thread.
  349. """
  350. # PEP-3333 states:
  351. #
  352. # The server or gateway must transmit the yielded bytestrings to the
  353. # client in an unbuffered fashion, completing the transmission of
  354. # each bytestring before requesting another one.
  355. #
  356. # This write() method is used for the imperative and (indirectly) for
  357. # the more familiar iterable-of-bytestrings WSGI mechanism. It uses
  358. # C{blockingCallFromThread} to schedule writes. This allows exceptions
  359. # to propagate up from the underlying HTTP implementation. However,
  360. # that underlying implementation does not, as yet, provide any way to
  361. # know if the written data has been transmitted, so this method
  362. # violates the above part of PEP-3333.
  363. #
  364. # PEP-3333 also says that a server may:
  365. #
  366. # Use a different thread to ensure that the block continues to be
  367. # transmitted while the application produces the next block.
  368. #
  369. # Which suggests that this is actually compliant with PEP-3333,
  370. # because writes are done in the reactor thread.
  371. #
  372. # However, providing some back-pressure may nevertheless be a Good
  373. # Thing at some point in the future.
  374. def wsgiWrite(started):
  375. if not started:
  376. self._sendResponseHeaders()
  377. self.request.write(data)
  378. try:
  379. return blockingCallFromThread(self.reactor, wsgiWrite, self.started)
  380. finally:
  381. self.started = True
  382. def _sendResponseHeaders(self):
  383. """
  384. Set the response code and response headers on the request object, but
  385. do not flush them. The caller is responsible for doing a write in
  386. order for anything to actually be written out in response to the
  387. request.
  388. This must be called in the I/O thread.
  389. """
  390. code, message = self.status.split(None, 1)
  391. code = int(code)
  392. self.request.setResponseCode(code, _wsgiStringToBytes(message))
  393. for name, value in self.headers:
  394. # Don't allow the application to control these required headers.
  395. if name.lower() not in ("server", "date"):
  396. self.request.responseHeaders.addRawHeader(
  397. _wsgiStringToBytes(name), _wsgiStringToBytes(value)
  398. )
  399. def start(self):
  400. """
  401. Start the WSGI application in the threadpool.
  402. This must be called in the I/O thread.
  403. """
  404. self.threadpool.callInThread(self.run)
  405. def run(self):
  406. """
  407. Call the WSGI application object, iterate it, and handle its output.
  408. This must be called in a non-I/O thread (ie, a WSGI application
  409. thread).
  410. """
  411. try:
  412. appIterator = self.application(self.environ, self.startResponse)
  413. for elem in appIterator:
  414. if elem:
  415. self.write(elem)
  416. if self._requestFinished:
  417. break
  418. close = getattr(appIterator, "close", None)
  419. if close is not None:
  420. close()
  421. except BaseException:
  422. def wsgiError(started, type, value, traceback):
  423. self._log.failure(
  424. "WSGI application error", failure=Failure(value, type, traceback)
  425. )
  426. if started:
  427. self.request.loseConnection()
  428. else:
  429. self.request.setResponseCode(INTERNAL_SERVER_ERROR)
  430. self.request.finish()
  431. self.reactor.callFromThread(wsgiError, self.started, *exc_info())
  432. else:
  433. def wsgiFinish(started):
  434. if not self._requestFinished:
  435. if not started:
  436. self._sendResponseHeaders()
  437. self.request.finish()
  438. self.reactor.callFromThread(wsgiFinish, self.started)
  439. self.started = True
  440. @implementer(IResource)
  441. class WSGIResource:
  442. """
  443. An L{IResource} implementation which delegates responsibility for all
  444. resources hierarchically inferior to it to a WSGI application.
  445. @ivar _reactor: An L{IReactorThreads} provider which will be passed on to
  446. L{_WSGIResponse} to schedule calls in the I/O thread.
  447. @ivar _threadpool: A L{ThreadPool} which will be passed on to
  448. L{_WSGIResponse} to run the WSGI application object.
  449. @ivar _application: The WSGI application object.
  450. """
  451. # Further resource segments are left up to the WSGI application object to
  452. # handle.
  453. isLeaf = True
  454. def __init__(self, reactor, threadpool, application):
  455. self._reactor = reactor
  456. self._threadpool = threadpool
  457. self._application = application
  458. def render(self, request):
  459. """
  460. Turn the request into the appropriate C{environ} C{dict} suitable to be
  461. passed to the WSGI application object and then pass it on.
  462. The WSGI application object is given almost complete control of the
  463. rendering process. C{NOT_DONE_YET} will always be returned in order
  464. and response completion will be dictated by the application object, as
  465. will the status, headers, and the response body.
  466. """
  467. response = _WSGIResponse(
  468. self._reactor, self._threadpool, self._application, request
  469. )
  470. response.start()
  471. return NOT_DONE_YET
  472. def getChildWithDefault(self, name, request):
  473. """
  474. Reject attempts to retrieve a child resource. All path segments beyond
  475. the one which refers to this resource are handled by the WSGI
  476. application object.
  477. """
  478. raise RuntimeError("Cannot get IResource children from WSGIResource")
  479. def putChild(self, path, child):
  480. """
  481. Reject attempts to add a child resource to this resource. The WSGI
  482. application object handles all path segments beneath this resource, so
  483. L{IResource} children can never be found.
  484. """
  485. raise RuntimeError("Cannot put IResource children under WSGIResource")
  486. __all__ = ["WSGIResource"]