_template_util.py 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. twisted.web.util and twisted.web.template merged to avoid cyclic deps
  5. """
  6. import io
  7. import linecache
  8. import warnings
  9. from collections import OrderedDict
  10. from html import escape
  11. from typing import (
  12. IO,
  13. Any,
  14. AnyStr,
  15. Callable,
  16. Dict,
  17. List,
  18. Mapping,
  19. Optional,
  20. Tuple,
  21. Union,
  22. cast,
  23. )
  24. from xml.sax import handler, make_parser
  25. from xml.sax.xmlreader import AttributesNSImpl, Locator
  26. from zope.interface import implementer
  27. from twisted.internet.defer import Deferred
  28. from twisted.logger import Logger
  29. from twisted.python import urlpath
  30. from twisted.python.failure import Failure
  31. from twisted.python.filepath import FilePath
  32. from twisted.python.reflect import fullyQualifiedName
  33. from twisted.web import resource
  34. from twisted.web._element import Element, renderer
  35. from twisted.web._flatten import Flattenable, flatten, flattenString
  36. from twisted.web._stan import CDATA, Comment, Tag, slot
  37. from twisted.web.iweb import IRenderable, IRequest, ITemplateLoader
  38. def _PRE(text):
  39. """
  40. Wraps <pre> tags around some text and HTML-escape it.
  41. This is here since once twisted.web.html was deprecated it was hard to
  42. migrate the html.PRE from current code to twisted.web.template.
  43. For new code consider using twisted.web.template.
  44. @return: Escaped text wrapped in <pre> tags.
  45. @rtype: C{str}
  46. """
  47. return f"<pre>{escape(text)}</pre>"
  48. def redirectTo(URL: bytes, request: IRequest) -> bytes:
  49. """
  50. Generate a redirect to the given location.
  51. @param URL: A L{bytes} giving the location to which to redirect.
  52. @param request: The request object to use to generate the redirect.
  53. @type request: L{IRequest<twisted.web.iweb.IRequest>} provider
  54. @raise TypeError: If the type of C{URL} a L{str} instead of L{bytes}.
  55. @return: A L{bytes} containing HTML which tries to convince the client
  56. agent
  57. to visit the new location even if it doesn't respect the I{FOUND}
  58. response code. This is intended to be returned from a render method,
  59. eg::
  60. def render_GET(self, request):
  61. return redirectTo(b"http://example.com/", request)
  62. """
  63. if not isinstance(URL, bytes):
  64. raise TypeError("URL must be bytes")
  65. request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
  66. request.redirect(URL)
  67. # FIXME: The URL should be HTML-escaped.
  68. # https://twistedmatrix.com/trac/ticket/9839
  69. content = b"""
  70. <html>
  71. <head>
  72. <meta http-equiv=\"refresh\" content=\"0;URL=%(url)s\">
  73. </head>
  74. <body bgcolor=\"#FFFFFF\" text=\"#000000\">
  75. <a href=\"%(url)s\">click here</a>
  76. </body>
  77. </html>
  78. """ % {
  79. b"url": URL
  80. }
  81. return content
  82. class Redirect(resource.Resource):
  83. """
  84. Resource that redirects to a specific URL.
  85. @ivar url: Redirect target URL to put in the I{Location} response header.
  86. @type url: L{bytes}
  87. """
  88. isLeaf = True
  89. def __init__(self, url: bytes):
  90. super().__init__()
  91. self.url = url
  92. def render(self, request):
  93. return redirectTo(self.url, request)
  94. def getChild(self, name, request):
  95. return self
  96. # FIXME: This is totally broken, see https://twistedmatrix.com/trac/ticket/9838
  97. class ChildRedirector(Redirect):
  98. isLeaf = False
  99. def __init__(self, url):
  100. # XXX is this enough?
  101. if (
  102. (url.find("://") == -1)
  103. and (not url.startswith(".."))
  104. and (not url.startswith("/"))
  105. ):
  106. raise ValueError(
  107. (
  108. "It seems you've given me a redirect (%s) that is a child of"
  109. " myself! That's not good, it'll cause an infinite redirect."
  110. )
  111. % url
  112. )
  113. Redirect.__init__(self, url)
  114. def getChild(self, name, request):
  115. newUrl = self.url
  116. if not newUrl.endswith("/"):
  117. newUrl += "/"
  118. newUrl += name
  119. return ChildRedirector(newUrl)
  120. class ParentRedirect(resource.Resource):
  121. """
  122. Redirect to the nearest directory and strip any query string.
  123. This generates redirects like::
  124. / \u2192 /
  125. /foo \u2192 /
  126. /foo?bar \u2192 /
  127. /foo/ \u2192 /foo/
  128. /foo/bar \u2192 /foo/
  129. /foo/bar?baz \u2192 /foo/
  130. However, the generated I{Location} header contains an absolute URL rather
  131. than a path.
  132. The response is the same regardless of HTTP method.
  133. """
  134. isLeaf = 1
  135. def render(self, request: IRequest) -> bytes:
  136. """
  137. Respond to all requests by redirecting to nearest directory.
  138. """
  139. here = str(urlpath.URLPath.fromRequest(request).here()).encode("ascii")
  140. return redirectTo(here, request)
  141. class DeferredResource(resource.Resource):
  142. """
  143. I wrap up a Deferred that will eventually result in a Resource
  144. object.
  145. """
  146. isLeaf = 1
  147. def __init__(self, d):
  148. resource.Resource.__init__(self)
  149. self.d = d
  150. def getChild(self, name, request):
  151. return self
  152. def render(self, request):
  153. self.d.addCallback(self._cbChild, request).addErrback(self._ebChild, request)
  154. from twisted.web.server import NOT_DONE_YET
  155. return NOT_DONE_YET
  156. def _cbChild(self, child, request):
  157. request.render(resource.getChildForRequest(child, request))
  158. def _ebChild(self, reason, request):
  159. request.processingFailed(reason)
  160. class _SourceLineElement(Element):
  161. """
  162. L{_SourceLineElement} is an L{IRenderable} which can render a single line of
  163. source code.
  164. @ivar number: A C{int} giving the line number of the source code to be
  165. rendered.
  166. @ivar source: A C{str} giving the source code to be rendered.
  167. """
  168. def __init__(self, loader, number, source):
  169. Element.__init__(self, loader)
  170. self.number = number
  171. self.source = source
  172. @renderer
  173. def sourceLine(self, request, tag):
  174. """
  175. Render the line of source as a child of C{tag}.
  176. """
  177. return tag(self.source.replace(" ", " \N{NO-BREAK SPACE}"))
  178. @renderer
  179. def lineNumber(self, request, tag):
  180. """
  181. Render the line number as a child of C{tag}.
  182. """
  183. return tag(str(self.number))
  184. class _SourceFragmentElement(Element):
  185. """
  186. L{_SourceFragmentElement} is an L{IRenderable} which can render several lines
  187. of source code near the line number of a particular frame object.
  188. @ivar frame: A L{Failure<twisted.python.failure.Failure>}-style frame object
  189. for which to load a source line to render. This is really a tuple
  190. holding some information from a frame object. See
  191. L{Failure.frames<twisted.python.failure.Failure>} for specifics.
  192. """
  193. def __init__(self, loader, frame):
  194. Element.__init__(self, loader)
  195. self.frame = frame
  196. def _getSourceLines(self):
  197. """
  198. Find the source line references by C{self.frame} and yield, in source
  199. line order, it and the previous and following lines.
  200. @return: A generator which yields two-tuples. Each tuple gives a source
  201. line number and the contents of that source line.
  202. """
  203. filename = self.frame[1]
  204. lineNumber = self.frame[2]
  205. for snipLineNumber in range(lineNumber - 1, lineNumber + 2):
  206. yield (snipLineNumber, linecache.getline(filename, snipLineNumber).rstrip())
  207. @renderer
  208. def sourceLines(self, request, tag):
  209. """
  210. Render the source line indicated by C{self.frame} and several
  211. surrounding lines. The active line will be given a I{class} of
  212. C{"snippetHighlightLine"}. Other lines will be given a I{class} of
  213. C{"snippetLine"}.
  214. """
  215. for lineNumber, sourceLine in self._getSourceLines():
  216. newTag = tag.clone()
  217. if lineNumber == self.frame[2]:
  218. cssClass = "snippetHighlightLine"
  219. else:
  220. cssClass = "snippetLine"
  221. loader = TagLoader(newTag(**{"class": cssClass}))
  222. yield _SourceLineElement(loader, lineNumber, sourceLine)
  223. class _FrameElement(Element):
  224. """
  225. L{_FrameElement} is an L{IRenderable} which can render details about one
  226. frame from a L{Failure<twisted.python.failure.Failure>}.
  227. @ivar frame: A L{Failure<twisted.python.failure.Failure>}-style frame object
  228. for which to load a source line to render. This is really a tuple
  229. holding some information from a frame object. See
  230. L{Failure.frames<twisted.python.failure.Failure>} for specifics.
  231. """
  232. def __init__(self, loader, frame):
  233. Element.__init__(self, loader)
  234. self.frame = frame
  235. @renderer
  236. def filename(self, request, tag):
  237. """
  238. Render the name of the file this frame references as a child of C{tag}.
  239. """
  240. return tag(self.frame[1])
  241. @renderer
  242. def lineNumber(self, request, tag):
  243. """
  244. Render the source line number this frame references as a child of
  245. C{tag}.
  246. """
  247. return tag(str(self.frame[2]))
  248. @renderer
  249. def function(self, request, tag):
  250. """
  251. Render the function name this frame references as a child of C{tag}.
  252. """
  253. return tag(self.frame[0])
  254. @renderer
  255. def source(self, request, tag):
  256. """
  257. Render the source code surrounding the line this frame references,
  258. replacing C{tag}.
  259. """
  260. return _SourceFragmentElement(TagLoader(tag), self.frame)
  261. class _StackElement(Element):
  262. """
  263. L{_StackElement} renders an L{IRenderable} which can render a list of frames.
  264. """
  265. def __init__(self, loader, stackFrames):
  266. Element.__init__(self, loader)
  267. self.stackFrames = stackFrames
  268. @renderer
  269. def frames(self, request, tag):
  270. """
  271. Render the list of frames in this L{_StackElement}, replacing C{tag}.
  272. """
  273. return [
  274. _FrameElement(TagLoader(tag.clone()), frame) for frame in self.stackFrames
  275. ]
  276. class _NSContext:
  277. """
  278. A mapping from XML namespaces onto their prefixes in the document.
  279. """
  280. def __init__(self, parent: Optional["_NSContext"] = None):
  281. """
  282. Pull out the parent's namespaces, if there's no parent then default to
  283. XML.
  284. """
  285. self.parent = parent
  286. if parent is not None:
  287. self.nss: Dict[Optional[str], Optional[str]] = OrderedDict(parent.nss)
  288. else:
  289. self.nss = {"http://www.w3.org/XML/1998/namespace": "xml"}
  290. def get(self, k: Optional[str], d: Optional[str] = None) -> Optional[str]:
  291. """
  292. Get a prefix for a namespace.
  293. @param d: The default prefix value.
  294. """
  295. return self.nss.get(k, d)
  296. def __setitem__(self, k: Optional[str], v: Optional[str]) -> None:
  297. """
  298. Proxy through to setting the prefix for the namespace.
  299. """
  300. self.nss.__setitem__(k, v)
  301. def __getitem__(self, k: Optional[str]) -> Optional[str]:
  302. """
  303. Proxy through to getting the prefix for the namespace.
  304. """
  305. return self.nss.__getitem__(k)
  306. TEMPLATE_NAMESPACE = "http://twistedmatrix.com/ns/twisted.web.template/0.1"
  307. class _ToStan(handler.ContentHandler, handler.EntityResolver):
  308. """
  309. A SAX parser which converts an XML document to the Twisted STAN
  310. Document Object Model.
  311. """
  312. def __init__(self, sourceFilename: Optional[str]):
  313. """
  314. @param sourceFilename: the filename the XML was loaded out of.
  315. """
  316. self.sourceFilename = sourceFilename
  317. self.prefixMap = _NSContext()
  318. self.inCDATA = False
  319. def setDocumentLocator(self, locator: Locator) -> None:
  320. """
  321. Set the document locator, which knows about line and character numbers.
  322. """
  323. self.locator = locator
  324. def startDocument(self) -> None:
  325. """
  326. Initialise the document.
  327. """
  328. # Depending on our active context, the element type can be Tag, slot
  329. # or str. Since mypy doesn't understand that context, it would be
  330. # a pain to not use Any here.
  331. self.document: List[Any] = []
  332. self.current = self.document
  333. self.stack: List[Any] = []
  334. self.xmlnsAttrs: List[Tuple[str, str]] = []
  335. def endDocument(self) -> None:
  336. """
  337. Document ended.
  338. """
  339. def processingInstruction(self, target: str, data: str) -> None:
  340. """
  341. Processing instructions are ignored.
  342. """
  343. def startPrefixMapping(self, prefix: Optional[str], uri: str) -> None:
  344. """
  345. Set up the prefix mapping, which maps fully qualified namespace URIs
  346. onto namespace prefixes.
  347. This gets called before startElementNS whenever an C{xmlns} attribute
  348. is seen.
  349. """
  350. self.prefixMap = _NSContext(self.prefixMap)
  351. self.prefixMap[uri] = prefix
  352. # Ignore the template namespace; we'll replace those during parsing.
  353. if uri == TEMPLATE_NAMESPACE:
  354. return
  355. # Add to a list that will be applied once we have the element.
  356. if prefix is None:
  357. self.xmlnsAttrs.append(("xmlns", uri))
  358. else:
  359. self.xmlnsAttrs.append(("xmlns:%s" % prefix, uri))
  360. def endPrefixMapping(self, prefix: Optional[str]) -> None:
  361. """
  362. "Pops the stack" on the prefix mapping.
  363. Gets called after endElementNS.
  364. """
  365. parent = self.prefixMap.parent
  366. assert parent is not None, "More prefix mapping ends than starts"
  367. self.prefixMap = parent
  368. def startElementNS(
  369. self,
  370. namespaceAndName: Tuple[str, str],
  371. qname: Optional[str],
  372. attrs: AttributesNSImpl,
  373. ) -> None:
  374. """
  375. Gets called when we encounter a new xmlns attribute.
  376. @param namespaceAndName: a (namespace, name) tuple, where name
  377. determines which type of action to take, if the namespace matches
  378. L{TEMPLATE_NAMESPACE}.
  379. @param qname: ignored.
  380. @param attrs: attributes on the element being started.
  381. """
  382. filename = self.sourceFilename
  383. lineNumber = self.locator.getLineNumber()
  384. columnNumber = self.locator.getColumnNumber()
  385. ns, name = namespaceAndName
  386. if ns == TEMPLATE_NAMESPACE:
  387. if name == "transparent":
  388. name = ""
  389. elif name == "slot":
  390. default: Optional[str]
  391. try:
  392. # Try to get the default value for the slot
  393. default = attrs[(None, "default")]
  394. except KeyError:
  395. # If there wasn't one, then use None to indicate no
  396. # default.
  397. default = None
  398. sl = slot(
  399. attrs[(None, "name")],
  400. default=default,
  401. filename=filename,
  402. lineNumber=lineNumber,
  403. columnNumber=columnNumber,
  404. )
  405. self.stack.append(sl)
  406. self.current.append(sl)
  407. self.current = sl.children
  408. return
  409. render = None
  410. ordered = OrderedDict(attrs)
  411. for k, v in list(ordered.items()):
  412. attrNS, justTheName = k
  413. if attrNS != TEMPLATE_NAMESPACE:
  414. continue
  415. if justTheName == "render":
  416. render = v
  417. del ordered[k]
  418. # nonTemplateAttrs is a dictionary mapping attributes that are *not* in
  419. # TEMPLATE_NAMESPACE to their values. Those in TEMPLATE_NAMESPACE were
  420. # just removed from 'attrs' in the loop immediately above. The key in
  421. # nonTemplateAttrs is either simply the attribute name (if it was not
  422. # specified as having a namespace in the template) or prefix:name,
  423. # preserving the xml namespace prefix given in the document.
  424. nonTemplateAttrs = OrderedDict()
  425. for (attrNs, attrName), v in ordered.items():
  426. nsPrefix = self.prefixMap.get(attrNs)
  427. if nsPrefix is None:
  428. attrKey = attrName
  429. else:
  430. attrKey = f"{nsPrefix}:{attrName}"
  431. nonTemplateAttrs[attrKey] = v
  432. if ns == TEMPLATE_NAMESPACE and name == "attr":
  433. if not self.stack:
  434. # TODO: define a better exception for this?
  435. raise AssertionError(
  436. f"<{{{TEMPLATE_NAMESPACE}}}attr> as top-level element"
  437. )
  438. if "name" not in nonTemplateAttrs:
  439. # TODO: same here
  440. raise AssertionError(
  441. f"<{{{TEMPLATE_NAMESPACE}}}attr> requires a name attribute"
  442. )
  443. el = Tag(
  444. "",
  445. render=render,
  446. filename=filename,
  447. lineNumber=lineNumber,
  448. columnNumber=columnNumber,
  449. )
  450. self.stack[-1].attributes[nonTemplateAttrs["name"]] = el
  451. self.stack.append(el)
  452. self.current = el.children
  453. return
  454. # Apply any xmlns attributes
  455. if self.xmlnsAttrs:
  456. nonTemplateAttrs.update(OrderedDict(self.xmlnsAttrs))
  457. self.xmlnsAttrs = []
  458. # Add the prefix that was used in the parsed template for non-template
  459. # namespaces (which will not be consumed anyway).
  460. if ns != TEMPLATE_NAMESPACE and ns is not None:
  461. prefix = self.prefixMap[ns]
  462. if prefix is not None:
  463. name = f"{self.prefixMap[ns]}:{name}"
  464. el = Tag(
  465. name,
  466. attributes=OrderedDict(
  467. cast(Mapping[Union[bytes, str], str], nonTemplateAttrs)
  468. ),
  469. render=render,
  470. filename=filename,
  471. lineNumber=lineNumber,
  472. columnNumber=columnNumber,
  473. )
  474. self.stack.append(el)
  475. self.current.append(el)
  476. self.current = el.children
  477. def characters(self, ch: str) -> None:
  478. """
  479. Called when we receive some characters. CDATA characters get passed
  480. through as is.
  481. """
  482. if self.inCDATA:
  483. self.stack[-1].append(ch)
  484. return
  485. self.current.append(ch)
  486. def endElementNS(self, name: Tuple[str, str], qname: Optional[str]) -> None:
  487. """
  488. A namespace tag is closed. Pop the stack, if there's anything left in
  489. it, otherwise return to the document's namespace.
  490. """
  491. self.stack.pop()
  492. if self.stack:
  493. self.current = self.stack[-1].children
  494. else:
  495. self.current = self.document
  496. def startDTD(self, name: str, publicId: str, systemId: str) -> None:
  497. """
  498. DTDs are ignored.
  499. """
  500. def endDTD(self, *args: object) -> None:
  501. """
  502. DTDs are ignored.
  503. """
  504. def startCDATA(self) -> None:
  505. """
  506. We're starting to be in a CDATA element, make a note of this.
  507. """
  508. self.inCDATA = True
  509. self.stack.append([])
  510. def endCDATA(self) -> None:
  511. """
  512. We're no longer in a CDATA element. Collect up the characters we've
  513. parsed and put them in a new CDATA object.
  514. """
  515. self.inCDATA = False
  516. comment = "".join(self.stack.pop())
  517. self.current.append(CDATA(comment))
  518. def comment(self, content: str) -> None:
  519. """
  520. Add an XML comment which we've encountered.
  521. """
  522. self.current.append(Comment(content))
  523. def _flatsaxParse(fl: Union[IO[AnyStr], str]) -> List["Flattenable"]:
  524. """
  525. Perform a SAX parse of an XML document with the _ToStan class.
  526. @param fl: The XML document to be parsed.
  527. @return: a C{list} of Stan objects.
  528. """
  529. parser = make_parser()
  530. parser.setFeature(handler.feature_validation, 0)
  531. parser.setFeature(handler.feature_namespaces, 1)
  532. parser.setFeature(handler.feature_external_ges, 0)
  533. parser.setFeature(handler.feature_external_pes, 0)
  534. s = _ToStan(getattr(fl, "name", None))
  535. parser.setContentHandler(s)
  536. parser.setEntityResolver(s)
  537. parser.setProperty(handler.property_lexical_handler, s)
  538. parser.parse(fl)
  539. return s.document
  540. @implementer(ITemplateLoader)
  541. class XMLString:
  542. """
  543. An L{ITemplateLoader} that loads and parses XML from a string.
  544. """
  545. def __init__(self, s: Union[str, bytes]):
  546. """
  547. Run the parser on a L{io.StringIO} copy of the string.
  548. @param s: The string from which to load the XML.
  549. @type s: L{str}, or a UTF-8 encoded L{bytes}.
  550. """
  551. if not isinstance(s, str):
  552. s = s.decode("utf8")
  553. self._loadedTemplate: List["Flattenable"] = _flatsaxParse(io.StringIO(s))
  554. """The loaded document."""
  555. def load(self) -> List["Flattenable"]:
  556. """
  557. Return the document.
  558. @return: the loaded document.
  559. """
  560. return self._loadedTemplate
  561. class FailureElement(Element):
  562. """
  563. L{FailureElement} is an L{IRenderable} which can render detailed information
  564. about a L{Failure<twisted.python.failure.Failure>}.
  565. @ivar failure: The L{Failure<twisted.python.failure.Failure>} instance which
  566. will be rendered.
  567. @since: 12.1
  568. """
  569. loader = XMLString(
  570. """
  571. <div xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">
  572. <style type="text/css">
  573. div.error {
  574. color: red;
  575. font-family: Verdana, Arial, helvetica, sans-serif;
  576. font-weight: bold;
  577. }
  578. div {
  579. font-family: Verdana, Arial, helvetica, sans-serif;
  580. }
  581. div.stackTrace {
  582. }
  583. div.frame {
  584. padding: 1em;
  585. background: white;
  586. border-bottom: thin black dashed;
  587. }
  588. div.frame:first-child {
  589. padding: 1em;
  590. background: white;
  591. border-top: thin black dashed;
  592. border-bottom: thin black dashed;
  593. }
  594. div.location {
  595. }
  596. span.function {
  597. font-weight: bold;
  598. font-family: "Courier New", courier, monospace;
  599. }
  600. div.snippet {
  601. margin-bottom: 0.5em;
  602. margin-left: 1em;
  603. background: #FFFFDD;
  604. }
  605. div.snippetHighlightLine {
  606. color: red;
  607. }
  608. span.code {
  609. font-family: "Courier New", courier, monospace;
  610. }
  611. </style>
  612. <div class="error">
  613. <span t:render="type" />: <span t:render="value" />
  614. </div>
  615. <div class="stackTrace" t:render="traceback">
  616. <div class="frame" t:render="frames">
  617. <div class="location">
  618. <span t:render="filename" />:<span t:render="lineNumber" /> in
  619. <span class="function" t:render="function" />
  620. </div>
  621. <div class="snippet" t:render="source">
  622. <div t:render="sourceLines">
  623. <span class="lineno" t:render="lineNumber" />
  624. <code class="code" t:render="sourceLine" />
  625. </div>
  626. </div>
  627. </div>
  628. </div>
  629. <div class="error">
  630. <span t:render="type" />: <span t:render="value" />
  631. </div>
  632. </div>
  633. """
  634. )
  635. def __init__(self, failure, loader=None):
  636. Element.__init__(self, loader)
  637. self.failure = failure
  638. @renderer
  639. def type(self, request, tag):
  640. """
  641. Render the exception type as a child of C{tag}.
  642. """
  643. return tag(fullyQualifiedName(self.failure.type))
  644. @renderer
  645. def value(self, request, tag):
  646. """
  647. Render the exception value as a child of C{tag}.
  648. """
  649. return tag(str(self.failure.value).encode("utf8"))
  650. @renderer
  651. def traceback(self, request, tag):
  652. """
  653. Render all the frames in the wrapped
  654. L{Failure<twisted.python.failure.Failure>}'s traceback stack, replacing
  655. C{tag}.
  656. """
  657. return _StackElement(TagLoader(tag), self.failure.frames)
  658. def formatFailure(myFailure):
  659. """
  660. Construct an HTML representation of the given failure.
  661. Consider using L{FailureElement} instead.
  662. @type myFailure: L{Failure<twisted.python.failure.Failure>}
  663. @rtype: L{bytes}
  664. @return: A string containing the HTML representation of the given failure.
  665. """
  666. result = []
  667. flattenString(None, FailureElement(myFailure)).addBoth(result.append)
  668. if isinstance(result[0], bytes):
  669. # Ensure the result string is all ASCII, for compatibility with the
  670. # default encoding expected by browsers.
  671. return result[0].decode("utf-8").encode("ascii", "xmlcharrefreplace")
  672. result[0].raiseException()
  673. # Go read the definition of NOT_DONE_YET. For lulz. This is totally
  674. # equivalent. And this turns out to be necessary, because trying to import
  675. # NOT_DONE_YET in this module causes a circular import which we cannot escape
  676. # from. From which we cannot escape. Etc. glyph is okay with this solution for
  677. # now, and so am I, as long as this comment stays to explain to future
  678. # maintainers what it means. ~ C.
  679. #
  680. # See http://twistedmatrix.com/trac/ticket/5557 for progress on fixing this.
  681. NOT_DONE_YET = 1
  682. _moduleLog = Logger()
  683. @implementer(ITemplateLoader)
  684. class TagLoader:
  685. """
  686. An L{ITemplateLoader} that loads an existing flattenable object.
  687. """
  688. def __init__(self, tag: "Flattenable"):
  689. """
  690. @param tag: The object which will be loaded.
  691. """
  692. self.tag: "Flattenable" = tag
  693. """The object which will be loaded."""
  694. def load(self) -> List["Flattenable"]:
  695. return [self.tag]
  696. @implementer(ITemplateLoader)
  697. class XMLFile:
  698. """
  699. An L{ITemplateLoader} that loads and parses XML from a file.
  700. """
  701. def __init__(self, path: FilePath[Any]):
  702. """
  703. Run the parser on a file.
  704. @param path: The file from which to load the XML.
  705. """
  706. if not isinstance(path, FilePath):
  707. warnings.warn( # type: ignore[unreachable]
  708. "Passing filenames or file objects to XMLFile is deprecated "
  709. "since Twisted 12.1. Pass a FilePath instead.",
  710. category=DeprecationWarning,
  711. stacklevel=2,
  712. )
  713. self._loadedTemplate: Optional[List["Flattenable"]] = None
  714. """The loaded document, or L{None}, if not loaded."""
  715. self._path: FilePath[Any] = path
  716. """The file that is being loaded from."""
  717. def _loadDoc(self) -> List["Flattenable"]:
  718. """
  719. Read and parse the XML.
  720. @return: the loaded document.
  721. """
  722. if not isinstance(self._path, FilePath):
  723. return _flatsaxParse(self._path) # type: ignore[unreachable]
  724. else:
  725. with self._path.open("r") as f:
  726. return _flatsaxParse(f)
  727. def __repr__(self) -> str:
  728. return f"<XMLFile of {self._path!r}>"
  729. def load(self) -> List["Flattenable"]:
  730. """
  731. Return the document, first loading it if necessary.
  732. @return: the loaded document.
  733. """
  734. if self._loadedTemplate is None:
  735. self._loadedTemplate = self._loadDoc()
  736. return self._loadedTemplate
  737. # Last updated October 2011, using W3Schools as a reference. Link:
  738. # http://www.w3schools.com/html5/html5_reference.asp
  739. # Note that <xmp> is explicitly omitted; its semantics do not work with
  740. # t.w.template and it is officially deprecated.
  741. VALID_HTML_TAG_NAMES = {
  742. "a",
  743. "abbr",
  744. "acronym",
  745. "address",
  746. "applet",
  747. "area",
  748. "article",
  749. "aside",
  750. "audio",
  751. "b",
  752. "base",
  753. "basefont",
  754. "bdi",
  755. "bdo",
  756. "big",
  757. "blockquote",
  758. "body",
  759. "br",
  760. "button",
  761. "canvas",
  762. "caption",
  763. "center",
  764. "cite",
  765. "code",
  766. "col",
  767. "colgroup",
  768. "command",
  769. "datalist",
  770. "dd",
  771. "del",
  772. "details",
  773. "dfn",
  774. "dir",
  775. "div",
  776. "dl",
  777. "dt",
  778. "em",
  779. "embed",
  780. "fieldset",
  781. "figcaption",
  782. "figure",
  783. "font",
  784. "footer",
  785. "form",
  786. "frame",
  787. "frameset",
  788. "h1",
  789. "h2",
  790. "h3",
  791. "h4",
  792. "h5",
  793. "h6",
  794. "head",
  795. "header",
  796. "hgroup",
  797. "hr",
  798. "html",
  799. "i",
  800. "iframe",
  801. "img",
  802. "input",
  803. "ins",
  804. "isindex",
  805. "keygen",
  806. "kbd",
  807. "label",
  808. "legend",
  809. "li",
  810. "link",
  811. "map",
  812. "mark",
  813. "menu",
  814. "meta",
  815. "meter",
  816. "nav",
  817. "noframes",
  818. "noscript",
  819. "object",
  820. "ol",
  821. "optgroup",
  822. "option",
  823. "output",
  824. "p",
  825. "param",
  826. "pre",
  827. "progress",
  828. "q",
  829. "rp",
  830. "rt",
  831. "ruby",
  832. "s",
  833. "samp",
  834. "script",
  835. "section",
  836. "select",
  837. "small",
  838. "source",
  839. "span",
  840. "strike",
  841. "strong",
  842. "style",
  843. "sub",
  844. "summary",
  845. "sup",
  846. "table",
  847. "tbody",
  848. "td",
  849. "textarea",
  850. "tfoot",
  851. "th",
  852. "thead",
  853. "time",
  854. "title",
  855. "tr",
  856. "tt",
  857. "u",
  858. "ul",
  859. "var",
  860. "video",
  861. "wbr",
  862. }
  863. class _TagFactory:
  864. """
  865. A factory for L{Tag} objects; the implementation of the L{tags} object.
  866. This allows for the syntactic convenience of C{from twisted.web.template
  867. import tags; tags.a(href="linked-page.html")}, where 'a' can be basically
  868. any HTML tag.
  869. The class is not exposed publicly because you only ever need one of these,
  870. and we already made it for you.
  871. @see: L{tags}
  872. """
  873. def __getattr__(self, tagName: str) -> Tag:
  874. if tagName == "transparent":
  875. return Tag("")
  876. # allow for E.del as E.del_
  877. tagName = tagName.rstrip("_")
  878. if tagName not in VALID_HTML_TAG_NAMES:
  879. raise AttributeError(f"unknown tag {tagName!r}")
  880. return Tag(tagName)
  881. tags = _TagFactory()
  882. def renderElement(
  883. request: IRequest,
  884. element: IRenderable,
  885. doctype: Optional[bytes] = b"<!DOCTYPE html>",
  886. _failElement: Optional[Callable[[Failure], "Element"]] = None,
  887. ) -> object:
  888. """
  889. Render an element or other L{IRenderable}.
  890. @param request: The L{IRequest} being rendered to.
  891. @param element: An L{IRenderable} which will be rendered.
  892. @param doctype: A L{bytes} which will be written as the first line of
  893. the request, or L{None} to disable writing of a doctype. The argument
  894. should not include a trailing newline and will default to the HTML5
  895. doctype C{'<!DOCTYPE html>'}.
  896. @returns: NOT_DONE_YET
  897. @since: 12.1
  898. """
  899. if doctype is not None:
  900. request.write(doctype)
  901. request.write(b"\n")
  902. if _failElement is None:
  903. _failElement = FailureElement
  904. d = flatten(request, element, request.write)
  905. def eb(failure: Failure) -> Optional[Deferred[None]]:
  906. _moduleLog.failure(
  907. "An error occurred while rendering the response.", failure=failure
  908. )
  909. site = getattr(request, "site", None)
  910. if site is not None and site.displayTracebacks:
  911. assert _failElement is not None
  912. return flatten(request, _failElement(failure), request.write)
  913. else:
  914. request.write(
  915. b'<div style="font-size:800%;'
  916. b"background-color:#FFF;"
  917. b"color:#F00"
  918. b'">An error occurred while rendering the response.</div>'
  919. )
  920. return None
  921. def finish(result: object, *, request: IRequest = request) -> object:
  922. request.finish()
  923. return result
  924. d.addErrback(eb)
  925. d.addBoth(finish)
  926. return NOT_DONE_YET