_stan.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. # -*- test-case-name: twisted.web.test.test_stan -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An s-expression-like syntax for expressing xml in pure python.
  6. Stan tags allow you to build XML documents using Python.
  7. Stan is a DOM, or Document Object Model, implemented using basic Python types
  8. and functions called "flatteners". A flattener is a function that knows how to
  9. turn an object of a specific type into something that is closer to an HTML
  10. string. Stan differs from the W3C DOM by not being as cumbersome and heavy
  11. weight. Since the object model is built using simple python types such as lists,
  12. strings, and dictionaries, the API is simpler and constructing a DOM less
  13. cumbersome.
  14. @var voidElements: the names of HTML 'U{void
  15. elements<http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#void-elements>}';
  16. those which can't have contents and can therefore be self-closing in the
  17. output.
  18. """
  19. from inspect import iscoroutine, isgenerator
  20. from typing import TYPE_CHECKING, Dict, List, Optional, Union
  21. from warnings import warn
  22. import attr
  23. if TYPE_CHECKING:
  24. from twisted.web.template import Flattenable
  25. @attr.s(hash=False, eq=False, auto_attribs=True)
  26. class slot:
  27. """
  28. Marker for markup insertion in a template.
  29. """
  30. name: str
  31. """
  32. The name of this slot.
  33. The key which must be used in L{Tag.fillSlots} to fill it.
  34. """
  35. children: List["Tag"] = attr.ib(init=False, factory=list)
  36. """
  37. The L{Tag} objects included in this L{slot}'s template.
  38. """
  39. default: Optional["Flattenable"] = None
  40. """
  41. The default contents of this slot, if it is left unfilled.
  42. If this is L{None}, an L{UnfilledSlot} will be raised, rather than
  43. L{None} actually being used.
  44. """
  45. filename: Optional[str] = None
  46. """
  47. The name of the XML file from which this tag was parsed.
  48. If it was not parsed from an XML file, L{None}.
  49. """
  50. lineNumber: Optional[int] = None
  51. """
  52. The line number on which this tag was encountered in the XML file
  53. from which it was parsed.
  54. If it was not parsed from an XML file, L{None}.
  55. """
  56. columnNumber: Optional[int] = None
  57. """
  58. The column number at which this tag was encountered in the XML file
  59. from which it was parsed.
  60. If it was not parsed from an XML file, L{None}.
  61. """
  62. @attr.s(hash=False, eq=False, repr=False, auto_attribs=True)
  63. class Tag:
  64. """
  65. A L{Tag} represents an XML tags with a tag name, attributes, and children.
  66. A L{Tag} can be constructed using the special L{twisted.web.template.tags}
  67. object, or it may be constructed directly with a tag name. L{Tag}s have a
  68. special method, C{__call__}, which makes representing trees of XML natural
  69. using pure python syntax.
  70. """
  71. tagName: Union[bytes, str]
  72. """
  73. The name of the represented element.
  74. For a tag like C{<div></div>}, this would be C{"div"}.
  75. """
  76. attributes: Dict[Union[bytes, str], "Flattenable"] = attr.ib(factory=dict)
  77. """The attributes of the element."""
  78. children: List["Flattenable"] = attr.ib(factory=list)
  79. """The contents of this C{Tag}."""
  80. render: Optional[str] = None
  81. """
  82. The name of the render method to use for this L{Tag}.
  83. This name will be looked up at render time by the
  84. L{twisted.web.template.Element} doing the rendering,
  85. via L{twisted.web.template.Element.lookupRenderMethod},
  86. to determine which method to call.
  87. """
  88. filename: Optional[str] = None
  89. """
  90. The name of the XML file from which this tag was parsed.
  91. If it was not parsed from an XML file, L{None}.
  92. """
  93. lineNumber: Optional[int] = None
  94. """
  95. The line number on which this tag was encountered in the XML file
  96. from which it was parsed.
  97. If it was not parsed from an XML file, L{None}.
  98. """
  99. columnNumber: Optional[int] = None
  100. """
  101. The column number at which this tag was encountered in the XML file
  102. from which it was parsed.
  103. If it was not parsed from an XML file, L{None}.
  104. """
  105. slotData: Optional[Dict[str, "Flattenable"]] = attr.ib(init=False, default=None)
  106. """
  107. The data which can fill slots.
  108. If present, a dictionary mapping slot names to renderable values.
  109. The values in this dict might be anything that can be present as
  110. the child of a L{Tag}: strings, lists, L{Tag}s, generators, etc.
  111. """
  112. def fillSlots(self, **slots: "Flattenable") -> "Tag":
  113. """
  114. Remember the slots provided at this position in the DOM.
  115. During the rendering of children of this node, slots with names in
  116. C{slots} will be rendered as their corresponding values.
  117. @return: C{self}. This enables the idiom C{return tag.fillSlots(...)} in
  118. renderers.
  119. """
  120. if self.slotData is None:
  121. self.slotData = {}
  122. self.slotData.update(slots)
  123. return self
  124. def __call__(self, *children: "Flattenable", **kw: "Flattenable") -> "Tag":
  125. """
  126. Add children and change attributes on this tag.
  127. This is implemented using __call__ because it then allows the natural
  128. syntax::
  129. table(tr1, tr2, width="100%", height="50%", border="1")
  130. Children may be other tag instances, strings, functions, or any other
  131. object which has a registered flatten.
  132. Attributes may be 'transparent' tag instances (so that
  133. C{a(href=transparent(data="foo", render=myhrefrenderer))} works),
  134. strings, functions, or any other object which has a registered
  135. flattener.
  136. If the attribute is a python keyword, such as 'class', you can add an
  137. underscore to the name, like 'class_'.
  138. There is one special keyword argument, 'render', which will be used as
  139. the name of the renderer and saved as the 'render' attribute of this
  140. instance, rather than the DOM 'render' attribute in the attributes
  141. dictionary.
  142. """
  143. self.children.extend(children)
  144. for k, v in kw.items():
  145. if k[-1] == "_":
  146. k = k[:-1]
  147. if k == "render":
  148. if not isinstance(v, str):
  149. raise TypeError(
  150. f'Value for "render" attribute must be str, got {v!r}'
  151. )
  152. self.render = v
  153. else:
  154. self.attributes[k] = v
  155. return self
  156. def _clone(self, obj: "Flattenable", deep: bool) -> "Flattenable":
  157. """
  158. Clone a C{Flattenable} object; used by L{Tag.clone}.
  159. Note that both lists and tuples are cloned into lists.
  160. @param obj: an object with a clone method, a list or tuple, or something
  161. which should be immutable.
  162. @param deep: whether to continue cloning child objects; i.e. the
  163. contents of lists, the sub-tags within a tag.
  164. @return: a clone of C{obj}.
  165. """
  166. if hasattr(obj, "clone"):
  167. return obj.clone(deep)
  168. elif isinstance(obj, (list, tuple)):
  169. return [self._clone(x, deep) for x in obj]
  170. elif isgenerator(obj):
  171. warn(
  172. "Cloning a Tag which contains a generator is unsafe, "
  173. "since the generator can be consumed only once; "
  174. "this is deprecated since Twisted 21.7.0 and will raise "
  175. "an exception in the future",
  176. DeprecationWarning,
  177. )
  178. return obj
  179. elif iscoroutine(obj):
  180. warn(
  181. "Cloning a Tag which contains a coroutine is unsafe, "
  182. "since the coroutine can run only once; "
  183. "this is deprecated since Twisted 21.7.0 and will raise "
  184. "an exception in the future",
  185. DeprecationWarning,
  186. )
  187. return obj
  188. else:
  189. return obj
  190. def clone(self, deep: bool = True) -> "Tag":
  191. """
  192. Return a clone of this tag. If deep is True, clone all of this tag's
  193. children. Otherwise, just shallow copy the children list without copying
  194. the children themselves.
  195. """
  196. if deep:
  197. newchildren = [self._clone(x, True) for x in self.children]
  198. else:
  199. newchildren = self.children[:]
  200. newattrs = self.attributes.copy()
  201. for key in newattrs.keys():
  202. newattrs[key] = self._clone(newattrs[key], True)
  203. newslotdata = None
  204. if self.slotData:
  205. newslotdata = self.slotData.copy()
  206. for key in newslotdata:
  207. newslotdata[key] = self._clone(newslotdata[key], True)
  208. newtag = Tag(
  209. self.tagName,
  210. attributes=newattrs,
  211. children=newchildren,
  212. render=self.render,
  213. filename=self.filename,
  214. lineNumber=self.lineNumber,
  215. columnNumber=self.columnNumber,
  216. )
  217. newtag.slotData = newslotdata
  218. return newtag
  219. def clear(self) -> "Tag":
  220. """
  221. Clear any existing children from this tag.
  222. """
  223. self.children = []
  224. return self
  225. def __repr__(self) -> str:
  226. rstr = ""
  227. if self.attributes:
  228. rstr += ", attributes=%r" % self.attributes
  229. if self.children:
  230. rstr += ", children=%r" % self.children
  231. return f"Tag({self.tagName!r}{rstr})"
  232. voidElements = (
  233. "img",
  234. "br",
  235. "hr",
  236. "base",
  237. "meta",
  238. "link",
  239. "param",
  240. "area",
  241. "input",
  242. "col",
  243. "basefont",
  244. "isindex",
  245. "frame",
  246. "command",
  247. "embed",
  248. "keygen",
  249. "source",
  250. "track",
  251. "wbs",
  252. )
  253. @attr.s(hash=False, eq=False, repr=False, auto_attribs=True)
  254. class CDATA:
  255. """
  256. A C{<![CDATA[]]>} block from a template. Given a separate representation in
  257. the DOM so that they may be round-tripped through rendering without losing
  258. information.
  259. """
  260. data: str
  261. """The data between "C{<![CDATA[}" and "C{]]>}"."""
  262. def __repr__(self) -> str:
  263. return f"CDATA({self.data!r})"
  264. @attr.s(hash=False, eq=False, repr=False, auto_attribs=True)
  265. class Comment:
  266. """
  267. A C{<!-- -->} comment from a template. Given a separate representation in
  268. the DOM so that they may be round-tripped through rendering without losing
  269. information.
  270. """
  271. data: str
  272. """The data between "C{<!--}" and "C{-->}"."""
  273. def __repr__(self) -> str:
  274. return f"Comment({self.data!r})"
  275. @attr.s(hash=False, eq=False, repr=False, auto_attribs=True)
  276. class CharRef:
  277. """
  278. A numeric character reference. Given a separate representation in the DOM
  279. so that non-ASCII characters may be output as pure ASCII.
  280. @since: 12.0
  281. """
  282. ordinal: int
  283. """The ordinal value of the unicode character to which this object refers."""
  284. def __repr__(self) -> str:
  285. return "CharRef(%d)" % (self.ordinal,)