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.

resource.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. # -*- test-case-name: twisted.web.test.test_web, twisted.web.test.test_resource -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Implementation of the lowest-level Resource class.
  6. See L{twisted.web.pages} for some utility implementations.
  7. """
  8. __all__ = [
  9. "IResource",
  10. "getChildForRequest",
  11. "Resource",
  12. "ErrorPage",
  13. "NoResource",
  14. "ForbiddenResource",
  15. "EncodingResourceWrapper",
  16. ]
  17. import warnings
  18. from zope.interface import Attribute, Interface, implementer
  19. from incremental import Version
  20. from twisted.python.compat import nativeString
  21. from twisted.python.components import proxyForInterface
  22. from twisted.python.deprecate import deprecatedModuleAttribute
  23. from twisted.python.reflect import prefixedMethodNames
  24. from twisted.web._responses import FORBIDDEN, NOT_FOUND
  25. from twisted.web.error import UnsupportedMethod
  26. class IResource(Interface):
  27. """
  28. A web resource.
  29. """
  30. isLeaf = Attribute(
  31. """
  32. Signal if this IResource implementor is a "leaf node" or not. If True,
  33. getChildWithDefault will not be called on this Resource.
  34. """
  35. )
  36. def getChildWithDefault(name, request):
  37. """
  38. Return a child with the given name for the given request.
  39. This is the external interface used by the Resource publishing
  40. machinery. If implementing IResource without subclassing
  41. Resource, it must be provided. However, if subclassing Resource,
  42. getChild overridden instead.
  43. @param name: A single path component from a requested URL. For example,
  44. a request for I{http://example.com/foo/bar} will result in calls to
  45. this method with C{b"foo"} and C{b"bar"} as values for this
  46. argument.
  47. @type name: C{bytes}
  48. @param request: A representation of all of the information about the
  49. request that is being made for this child.
  50. @type request: L{twisted.web.server.Request}
  51. """
  52. def putChild(path: bytes, child: "IResource") -> None:
  53. """
  54. Put a child L{IResource} implementor at the given path.
  55. @param path: A single path component, to be interpreted relative to the
  56. path this resource is found at, at which to put the given child.
  57. For example, if resource A can be found at I{http://example.com/foo}
  58. then a call like C{A.putChild(b"bar", B)} will make resource B
  59. available at I{http://example.com/foo/bar}.
  60. The path component is I{not} URL-encoded -- pass C{b'foo bar'}
  61. rather than C{b'foo%20bar'}.
  62. """
  63. def render(request):
  64. """
  65. Render a request. This is called on the leaf resource for a request.
  66. @return: Either C{server.NOT_DONE_YET} to indicate an asynchronous or a
  67. C{bytes} instance to write as the response to the request. If
  68. C{NOT_DONE_YET} is returned, at some point later (for example, in a
  69. Deferred callback) call C{request.write(b"<html>")} to write data to
  70. the request, and C{request.finish()} to send the data to the
  71. browser.
  72. @raise twisted.web.error.UnsupportedMethod: If the HTTP verb
  73. requested is not supported by this resource.
  74. """
  75. def getChildForRequest(resource, request):
  76. """
  77. Traverse resource tree to find who will handle the request.
  78. """
  79. while request.postpath and not resource.isLeaf:
  80. pathElement = request.postpath.pop(0)
  81. request.prepath.append(pathElement)
  82. resource = resource.getChildWithDefault(pathElement, request)
  83. return resource
  84. @implementer(IResource)
  85. class Resource:
  86. """
  87. Define a web-accessible resource.
  88. This serves two main purposes: one is to provide a standard representation
  89. for what HTTP specification calls an 'entity', and the other is to provide
  90. an abstract directory structure for URL retrieval.
  91. """
  92. entityType = IResource
  93. server = None
  94. def __init__(self):
  95. """
  96. Initialize.
  97. """
  98. self.children = {}
  99. isLeaf = 0
  100. ### Abstract Collection Interface
  101. def listStaticNames(self):
  102. return list(self.children.keys())
  103. def listStaticEntities(self):
  104. return list(self.children.items())
  105. def listNames(self):
  106. return list(self.listStaticNames()) + self.listDynamicNames()
  107. def listEntities(self):
  108. return list(self.listStaticEntities()) + self.listDynamicEntities()
  109. def listDynamicNames(self):
  110. return []
  111. def listDynamicEntities(self, request=None):
  112. return []
  113. def getStaticEntity(self, name):
  114. return self.children.get(name)
  115. def getDynamicEntity(self, name, request):
  116. if name not in self.children:
  117. return self.getChild(name, request)
  118. else:
  119. return None
  120. def delEntity(self, name):
  121. del self.children[name]
  122. def reallyPutEntity(self, name, entity):
  123. self.children[name] = entity
  124. # Concrete HTTP interface
  125. def getChild(self, path, request):
  126. """
  127. Retrieve a 'child' resource from me.
  128. Implement this to create dynamic resource generation -- resources which
  129. are always available may be registered with self.putChild().
  130. This will not be called if the class-level variable 'isLeaf' is set in
  131. your subclass; instead, the 'postpath' attribute of the request will be
  132. left as a list of the remaining path elements.
  133. For example, the URL /foo/bar/baz will normally be::
  134. | site.resource.getChild('foo').getChild('bar').getChild('baz').
  135. However, if the resource returned by 'bar' has isLeaf set to true, then
  136. the getChild call will never be made on it.
  137. Parameters and return value have the same meaning and requirements as
  138. those defined by L{IResource.getChildWithDefault}.
  139. """
  140. return _UnsafeNoResource()
  141. def getChildWithDefault(self, path, request):
  142. """
  143. Retrieve a static or dynamically generated child resource from me.
  144. First checks if a resource was added manually by putChild, and then
  145. call getChild to check for dynamic resources. Only override if you want
  146. to affect behaviour of all child lookups, rather than just dynamic
  147. ones.
  148. This will check to see if I have a pre-registered child resource of the
  149. given name, and call getChild if I do not.
  150. @see: L{IResource.getChildWithDefault}
  151. """
  152. if path in self.children:
  153. return self.children[path]
  154. return self.getChild(path, request)
  155. def getChildForRequest(self, request):
  156. """
  157. Deprecated in favor of L{getChildForRequest}.
  158. @see: L{twisted.web.resource.getChildForRequest}.
  159. """
  160. warnings.warn(
  161. "Please use module level getChildForRequest.", DeprecationWarning, 2
  162. )
  163. return getChildForRequest(self, request)
  164. def putChild(self, path: bytes, child: IResource) -> None:
  165. """
  166. Register a static child.
  167. You almost certainly don't want '/' in your path. If you
  168. intended to have the root of a folder, e.g. /foo/, you want
  169. path to be ''.
  170. @param path: A single path component.
  171. @param child: The child resource to register.
  172. @see: L{IResource.putChild}
  173. """
  174. if not isinstance(path, bytes):
  175. raise TypeError(f"Path segment must be bytes, but {path!r} is {type(path)}")
  176. self.children[path] = child
  177. # IResource is incomplete and doesn't mention this server attribute, see
  178. # https://github.com/twisted/twisted/issues/11717
  179. child.server = self.server # type: ignore[attr-defined]
  180. def render(self, request):
  181. """
  182. Render a given resource. See L{IResource}'s render method.
  183. I delegate to methods of self with the form 'render_METHOD'
  184. where METHOD is the HTTP that was used to make the
  185. request. Examples: render_GET, render_HEAD, render_POST, and
  186. so on. Generally you should implement those methods instead of
  187. overriding this one.
  188. render_METHOD methods are expected to return a byte string which will be
  189. the rendered page, unless the return value is C{server.NOT_DONE_YET}, in
  190. which case it is this class's responsibility to write the results using
  191. C{request.write(data)} and then call C{request.finish()}.
  192. Old code that overrides render() directly is likewise expected
  193. to return a byte string or NOT_DONE_YET.
  194. @see: L{IResource.render}
  195. """
  196. m = getattr(self, "render_" + nativeString(request.method), None)
  197. if not m:
  198. try:
  199. allowedMethods = self.allowedMethods
  200. except AttributeError:
  201. allowedMethods = _computeAllowedMethods(self)
  202. raise UnsupportedMethod(allowedMethods)
  203. return m(request)
  204. def render_HEAD(self, request):
  205. """
  206. Default handling of HEAD method.
  207. I just return self.render_GET(request). When method is HEAD,
  208. the framework will handle this correctly.
  209. """
  210. return self.render_GET(request)
  211. def _computeAllowedMethods(resource):
  212. """
  213. Compute the allowed methods on a C{Resource} based on defined render_FOO
  214. methods. Used when raising C{UnsupportedMethod} but C{Resource} does
  215. not define C{allowedMethods} attribute.
  216. """
  217. allowedMethods = []
  218. for name in prefixedMethodNames(resource.__class__, "render_"):
  219. # Potentially there should be an API for encode('ascii') in this
  220. # situation - an API for taking a Python native string (bytes on Python
  221. # 2, text on Python 3) and returning a socket-compatible string type.
  222. allowedMethods.append(name.encode("ascii"))
  223. return allowedMethods
  224. class _UnsafeErrorPage(Resource):
  225. """
  226. L{_UnsafeErrorPage}, publicly available via the deprecated alias
  227. C{ErrorPage}, is a resource which responds with a particular
  228. (parameterized) status and a body consisting of HTML containing some
  229. descriptive text. This is useful for rendering simple error pages.
  230. Deprecated in Twisted 22.10.0 because it permits HTML injection; use
  231. L{twisted.web.pages.errorPage} instead.
  232. @ivar template: A native string which will have a dictionary interpolated
  233. into it to generate the response body. The dictionary has the following
  234. keys:
  235. - C{"code"}: The status code passed to L{_UnsafeErrorPage.__init__}.
  236. - C{"brief"}: The brief description passed to
  237. L{_UnsafeErrorPage.__init__}.
  238. - C{"detail"}: The detailed description passed to
  239. L{_UnsafeErrorPage.__init__}.
  240. @ivar code: An integer status code which will be used for the response.
  241. @type code: C{int}
  242. @ivar brief: A short string which will be included in the response body as
  243. the page title.
  244. @type brief: C{str}
  245. @ivar detail: A longer string which will be included in the response body.
  246. @type detail: C{str}
  247. """
  248. template = """
  249. <html>
  250. <head><title>%(code)s - %(brief)s</title></head>
  251. <body>
  252. <h1>%(brief)s</h1>
  253. <p>%(detail)s</p>
  254. </body>
  255. </html>
  256. """
  257. def __init__(self, status, brief, detail):
  258. Resource.__init__(self)
  259. self.code = status
  260. self.brief = brief
  261. self.detail = detail
  262. def render(self, request):
  263. request.setResponseCode(self.code)
  264. request.setHeader(b"content-type", b"text/html; charset=utf-8")
  265. interpolated = self.template % dict(
  266. code=self.code, brief=self.brief, detail=self.detail
  267. )
  268. if isinstance(interpolated, str):
  269. return interpolated.encode("utf-8")
  270. return interpolated
  271. def getChild(self, chnam, request):
  272. return self
  273. class _UnsafeNoResource(_UnsafeErrorPage):
  274. """
  275. L{_UnsafeNoResource}, publicly available via the deprecated alias
  276. C{NoResource}, is a specialization of L{_UnsafeErrorPage} which
  277. returns the HTTP response code I{NOT FOUND}.
  278. Deprecated in Twisted 22.10.0 because it permits HTML injection; use
  279. L{twisted.web.pages.notFound} instead.
  280. """
  281. def __init__(self, message="Sorry. No luck finding that resource."):
  282. _UnsafeErrorPage.__init__(self, NOT_FOUND, "No Such Resource", message)
  283. class _UnsafeForbiddenResource(_UnsafeErrorPage):
  284. """
  285. L{_UnsafeForbiddenResource}, publicly available via the deprecated alias
  286. C{ForbiddenResource} is a specialization of L{_UnsafeErrorPage} which
  287. returns the I{FORBIDDEN} HTTP response code.
  288. Deprecated in Twisted 22.10.0 because it permits HTML injection; use
  289. L{twisted.web.pages.forbidden} instead.
  290. """
  291. def __init__(self, message="Sorry, resource is forbidden."):
  292. _UnsafeErrorPage.__init__(self, FORBIDDEN, "Forbidden Resource", message)
  293. # Deliberately undocumented public aliases. See GHSA-vg46-2rrj-3647.
  294. ErrorPage = _UnsafeErrorPage
  295. NoResource = _UnsafeNoResource
  296. ForbiddenResource = _UnsafeForbiddenResource
  297. deprecatedModuleAttribute(
  298. Version("Twisted", 22, 10, 0),
  299. "Use twisted.web.pages.errorPage instead, which properly escapes HTML.",
  300. __name__,
  301. "ErrorPage",
  302. )
  303. deprecatedModuleAttribute(
  304. Version("Twisted", 22, 10, 0),
  305. "Use twisted.web.pages.notFound instead, which properly escapes HTML.",
  306. __name__,
  307. "NoResource",
  308. )
  309. deprecatedModuleAttribute(
  310. Version("Twisted", 22, 10, 0),
  311. "Use twisted.web.pages.forbidden instead, which properly escapes HTML.",
  312. __name__,
  313. "ForbiddenResource",
  314. )
  315. class _IEncodingResource(Interface):
  316. """
  317. A resource which knows about L{_IRequestEncoderFactory}.
  318. @since: 12.3
  319. """
  320. def getEncoder(request):
  321. """
  322. Parse the request and return an encoder if applicable, using
  323. L{_IRequestEncoderFactory.encoderForRequest}.
  324. @return: A L{_IRequestEncoder}, or L{None}.
  325. """
  326. @implementer(_IEncodingResource)
  327. class EncodingResourceWrapper(proxyForInterface(IResource)): # type: ignore[misc]
  328. """
  329. Wrap a L{IResource}, potentially applying an encoding to the response body
  330. generated.
  331. Note that the returned children resources won't be wrapped, so you have to
  332. explicitly wrap them if you want the encoding to be applied.
  333. @ivar encoders: A list of
  334. L{_IRequestEncoderFactory<twisted.web.iweb._IRequestEncoderFactory>}
  335. returning L{_IRequestEncoder<twisted.web.iweb._IRequestEncoder>} that
  336. may transform the data passed to C{Request.write}. The list must be
  337. sorted in order of priority: the first encoder factory handling the
  338. request will prevent the others from doing the same.
  339. @type encoders: C{list}.
  340. @since: 12.3
  341. """
  342. def __init__(self, original, encoders):
  343. super().__init__(original)
  344. self._encoders = encoders
  345. def getEncoder(self, request):
  346. """
  347. Browser the list of encoders looking for one applicable encoder.
  348. """
  349. for encoderFactory in self._encoders:
  350. encoder = encoderFactory.encoderForRequest(request)
  351. if encoder is not None:
  352. return encoder