resource.py 13 KB

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