| 1 |
""" |
| 2 |
Some classes adapting twisted.web (t.w) to make it "basically" work with |
| 3 |
twisted templates and rend.Pages. |
| 4 |
|
| 5 |
See porting guide in the README. |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import io |
| 15 |
import itertools |
| 16 |
import sys |
| 17 |
|
| 18 |
from xml.sax import make_parser, handler |
| 19 |
|
| 20 |
from twisted.internet import defer |
| 21 |
from twisted.python.filepath import FilePath |
| 22 |
from twisted.web import resource |
| 23 |
from twisted.web import server |
| 24 |
from twisted.web import template |
| 25 |
|
| 26 |
from .twistedpatch import Raw, _ToStan, _NSContext, Tag |
| 27 |
|
| 28 |
NEVOW_NS = 'http://nevow.com/ns/nevow/0.1' |
| 29 |
TWISTED_NS = 'http://twistedmatrix.com/ns/twisted.web.template/0.1' |
| 30 |
|
| 31 |
NAMESPACE_MAPPING = {NEVOW_NS: TWISTED_NS} |
| 32 |
|
| 33 |
# ELEMENT_MAPPING is only consulted if the namespace is in |
| 34 |
# NAMESPACE_MAPPING, so we can be a bit cavalier here. |
| 35 |
ELEMENT_MAPPING = { |
| 36 |
"invisible": "transparent", |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
class NoDataError(Exception): |
| 41 |
"""is raised when no data can be found for a tag during |
| 42 |
flattening. |
| 43 |
""" |
| 44 |
pass |
| 45 |
|
| 46 |
|
| 47 |
class MyToStan(_ToStan): |
| 48 |
"""A SAX parser unifying nevow and twisted.web namespaces. |
| 49 |
|
| 50 |
We also map invisible (nevow) to transparent (t.w). |
| 51 |
""" |
| 52 |
def __init__(self, sourceFilename): |
| 53 |
_ToStan.__init__(self, sourceFilename) |
| 54 |
self.prefixMap = _NSContext() |
| 55 |
self.prefixMap[NEVOW_NS] = "nevow" |
| 56 |
self.prefixMap[TWISTED_NS] = "nevow" |
| 57 |
|
| 58 |
def startPrefixMapping(self, prefix, uri): |
| 59 |
# overridden to swallow attempts to map prefixes for our |
| 60 |
# standard namespaces |
| 61 |
if uri==NEVOW_NS or uri==TWISTED_NS: |
| 62 |
self.prefixMap = _NSContext(self.prefixMap) |
| 63 |
return |
| 64 |
else: |
| 65 |
if prefix=="nevow": |
| 66 |
raise Exception("You may not bind the nevow prefix" |
| 67 |
" to a non-twisted or non-nevow URI") |
| 68 |
_ToStan.startPrefixMapping(self, prefix, uri) |
| 69 |
|
| 70 |
def startElementNS(self, namespaceAndName, qName, attrs): |
| 71 |
# regrettably, we also need to map attribute namespaces; |
| 72 |
# alternative: replace parent's startElementNS entirely. Hm. |
| 73 |
for attrNS, attrName in list(attrs.keys()): |
| 74 |
if attrNS in NAMESPACE_MAPPING: |
| 75 |
attrs._attrs[(NAMESPACE_MAPPING[attrNS], attrName) |
| 76 |
] = attrs._attrs.pop((attrNS, attrName)) |
| 77 |
|
| 78 |
ns, name = namespaceAndName |
| 79 |
if ns in NAMESPACE_MAPPING: |
| 80 |
ns = NAMESPACE_MAPPING[ns] |
| 81 |
name = ELEMENT_MAPPING.get(name, name) |
| 82 |
|
| 83 |
# twisted web blindly discards attributes when constructing |
| 84 |
# n:attr; we need n:data, at least, so I need to copy and fix |
| 85 |
# the code |
| 86 |
if ns==TWISTED_NS and name=='attr': |
| 87 |
if not self.stack or (None, 'name') not in attrs: |
| 88 |
raise AssertionError( |
| 89 |
'<attr> usage error') |
| 90 |
|
| 91 |
fixedAttrs = {} |
| 92 |
for (ns, attName), val in list(attrs.items()): |
| 93 |
if ns: |
| 94 |
fixedAttrs["%s:%s"%( |
| 95 |
self.prefixMap[ns], attName)] = val |
| 96 |
else: |
| 97 |
fixedAttrs[attName] = val |
| 98 |
|
| 99 |
el = Tag('', |
| 100 |
render=attrs.get((TWISTED_NS, 'render')), |
| 101 |
attributes=fixedAttrs, |
| 102 |
filename=self.sourceFilename, |
| 103 |
lineNumber=self.locator.getLineNumber()) |
| 104 |
self.stack[-1].attributes[attrs[None, 'name']] = el |
| 105 |
self.stack.append(el) |
| 106 |
self.current = el.children |
| 107 |
return |
| 108 |
|
| 109 |
if ns==TWISTED_NS and name=='invisible': |
| 110 |
name = 'transparent' |
| 111 |
|
| 112 |
return _ToStan.startElementNS(self, |
| 113 |
(ns, name), |
| 114 |
qName, |
| 115 |
attrs) |
| 116 |
|
| 117 |
|
| 118 |
def _flatsaxParse(fl): |
| 119 |
"""A copy of t.w.template._flatsaxParse that lets me use my own |
| 120 |
_ToStan |
| 121 |
""" |
| 122 |
parser = make_parser() |
| 123 |
parser.setFeature(handler.feature_validation, 0) |
| 124 |
parser.setFeature(handler.feature_namespaces, 1) |
| 125 |
parser.setFeature(handler.feature_external_ges, 0) |
| 126 |
parser.setFeature(handler.feature_external_pes, 0) |
| 127 |
|
| 128 |
s = MyToStan(getattr(fl, "name", None)) |
| 129 |
parser.setContentHandler(s) |
| 130 |
parser.setEntityResolver(s) |
| 131 |
parser.setProperty(handler.property_lexical_handler, s) |
| 132 |
|
| 133 |
parser.parse(fl) |
| 134 |
|
| 135 |
return s.document |
| 136 |
|
| 137 |
|
| 138 |
class XMLFile(template.XMLFile): |
| 139 |
"""a t.w.template.XMLFile able to load nevow templates |
| 140 |
|
| 141 |
...to some extent; we accept both nevow and twisted.web namespace |
| 142 |
We also unify namespaces prefix on attributes for both to nevow: |
| 143 |
for simpler handling in later processing. Yes, this will break |
| 144 |
if someone binds nevow: to some other namespace. Don't do that, then. |
| 145 |
""" |
| 146 |
def _loadDoc(self): |
| 147 |
# overridden to inject my _flatsaxParse; otherwise, it's a copy |
| 148 |
# of template.XMLFile.loadDoc |
| 149 |
if not isinstance(self._path, FilePath): |
| 150 |
return _flatsaxParse(self._path) |
| 151 |
else: |
| 152 |
with self._path.open('r') as f: |
| 153 |
return _flatsaxParse(f) |
| 154 |
|
| 155 |
|
| 156 |
class XMLString(template.XMLString): |
| 157 |
"""as XMLFile, just for strings. |
| 158 |
|
| 159 |
Again, we override to let us pass in our own parser. |
| 160 |
""" |
| 161 |
def __init__(self, s): |
| 162 |
if isinstance(s, str): |
| 163 |
s = s.encode('utf8') |
| 164 |
self._loadedTemplate = _flatsaxParse(io.BytesIO(s)) |
| 165 |
|
| 166 |
|
| 167 |
class Passthrough(Raw): |
| 168 |
"""a stan-like tag that inserts its content literally into the |
| 169 |
target document. |
| 170 |
|
| 171 |
No escaping will we done, so if what you pass in is not XML, you'll |
| 172 |
have a malformed result. |
| 173 |
|
| 174 |
This is tags.xml from nevow born again; hence, use it as T.xml |
| 175 |
from template.tags. |
| 176 |
""" |
| 177 |
def __init__(self, content): |
| 178 |
if isinstance(content, str): |
| 179 |
content = content.encode("utf-8") |
| 180 |
if not isinstance(content, bytes): |
| 181 |
raise Exception("xml content must be a byte string, not %s"% |
| 182 |
content) |
| 183 |
self.content = content |
| 184 |
|
| 185 |
def getContent(self): |
| 186 |
return self.content |
| 187 |
|
| 188 |
template.tags.xml = Passthrough |
| 189 |
|
| 190 |
|
| 191 |
def iterChildren(tag, |
| 192 |
stopRenders=frozenset(["sequence", "mapping"]), |
| 193 |
stopAtData=False): |
| 194 |
"""yields the Tag-typed descendents of tag preorder. |
| 195 |
|
| 196 |
stopRenderer is a set of renderer names at which traversal does |
| 197 |
not recurse; this is generally where data "changes" externally |
| 198 |
for most of our use cases here. |
| 199 |
""" |
| 200 |
# somewhat sadly, n:attr ends up in attributes. So, we need to |
| 201 |
# iterate over the attribute values, too. Sigh. |
| 202 |
for t in itertools.chain( |
| 203 |
tag.children, |
| 204 |
iter(tag.attributes.values())): |
| 205 |
if isinstance(t, template.Tag): |
| 206 |
|
| 207 |
yield t |
| 208 |
|
| 209 |
if (t.render is None or t.render not in stopRenders |
| 210 |
) and not (stopAtData and "nevow:data" in t.attributes): |
| 211 |
for c in iterChildren(t, stopRenders, stopAtData): |
| 212 |
yield c |
| 213 |
|
| 214 |
|
| 215 |
def locatePatterns(tag, |
| 216 |
searchPatterns=[], |
| 217 |
stopRenders=["sequence", "mapping"]): |
| 218 |
"""returns all descendents of tags for which nevow:pattern is in |
| 219 |
searchPatterns. |
| 220 |
|
| 221 |
The return value is a dictionary mapping each item in searchPatterns |
| 222 |
to the pattern name. |
| 223 |
|
| 224 |
This recursively traverses the children of tag, but recursion will stop |
| 225 |
when tags have nevow:render attributes in stopRenders. |
| 226 |
""" |
| 227 |
searchPatterns, stopRenders = set(searchPatterns), set(stopRenders) |
| 228 |
res = dict((p, []) for p in searchPatterns) |
| 229 |
|
| 230 |
for t in iterChildren(tag, stopRenders): |
| 231 |
attrs = t.attributes |
| 232 |
if attrs.get("nevow:pattern") in searchPatterns: |
| 233 |
pat = t.clone() |
| 234 |
res[attrs["nevow:pattern"]].append(pat) |
| 235 |
del pat.attributes["nevow:pattern"] |
| 236 |
return res |
| 237 |
|
| 238 |
|
| 239 |
def addNevowAttributes(tag, **kwargs): |
| 240 |
"""adds kwargs as n:key to a clone of tag's attrs. |
| 241 |
|
| 242 |
This is so you can add n:pattern, n:data and friends even within |
| 243 |
a stan DOM. |
| 244 |
""" |
| 245 |
res = tag.clone() |
| 246 |
for k, v in list(kwargs.items()): |
| 247 |
res.attributes["nevow:"+k] = v |
| 248 |
return res |
| 249 |
|
| 250 |
|
| 251 |
class CommonRenderers(object): |
| 252 |
"""A container for some basic renderers we want on all active |
| 253 |
elements. |
| 254 |
|
| 255 |
This is basically what nevow had. |
| 256 |
""" |
| 257 |
@template.renderer |
| 258 |
def sequence(self, request, tag): |
| 259 |
toProcess = tag.slotData |
| 260 |
|
| 261 |
patterns = locatePatterns(tag, |
| 262 |
["item", "empty", "separator", "header", "footer"], |
| 263 |
["sequence"]) |
| 264 |
if not patterns["item"]: |
| 265 |
patterns["item"] = [template.tags.transparent] |
| 266 |
tagIterator = iter(patterns["item"]) |
| 267 |
|
| 268 |
newTag = tag.clone(True).clear() |
| 269 |
newTag.render = None |
| 270 |
|
| 271 |
if patterns["header"]: |
| 272 |
newTag[patterns["header"]] |
| 273 |
|
| 274 |
for item in toProcess: |
| 275 |
try: |
| 276 |
nextTag = next(tagIterator) |
| 277 |
except StopIteration: |
| 278 |
newTag(patterns["separator"]) |
| 279 |
tagIterator = iter(patterns["item"]) |
| 280 |
nextTag = next(tagIterator) |
| 281 |
newTag(nextTag.clone(True, item)) |
| 282 |
|
| 283 |
if newTag.children or not patterns["empty"]: |
| 284 |
if patterns["footer"]: |
| 285 |
newTag[patterns["footer"]] |
| 286 |
|
| 287 |
return newTag |
| 288 |
else: |
| 289 |
return patterns["empty"] |
| 290 |
|
| 291 |
@template.renderer |
| 292 |
def mapping(self, request, tag): |
| 293 |
return tag.fillSlots(**tag.slotData) |
| 294 |
|
| 295 |
def data_key(self, keyName): |
| 296 |
"""returns data[keyName]; of course, this only works if the current |
| 297 |
data is a dict. |
| 298 |
""" |
| 299 |
def _(request, tag): |
| 300 |
return tag.slotData[keyName] |
| 301 |
return _ |
| 302 |
|
| 303 |
@template.renderer |
| 304 |
def string(self, request, tag): |
| 305 |
return tag[str(tag.slotData)] |
| 306 |
|
| 307 |
@template.renderer |
| 308 |
def xml(self, request, tag): |
| 309 |
return tag[template.tags.xml(tag.slotData)] |
| 310 |
|
| 311 |
@template.renderer |
| 312 |
def passthrough(self, request, tag): |
| 313 |
"""inserts the current data into the stan tree. |
| 314 |
|
| 315 |
That's nevow's "data" renderer; but it's more limited in that |
| 316 |
t.w's flattener is more limited. |
| 317 |
""" |
| 318 |
return tag[tag.slotData] |
| 319 |
|
| 320 |
def lookupRenderMethod(self, name): |
| 321 |
if callable(name): |
| 322 |
return name |
| 323 |
|
| 324 |
if " " in name: |
| 325 |
parts = name.split() |
| 326 |
method = template.renderer.get(self, parts[0], None) |
| 327 |
if method is None: |
| 328 |
raise Exception("Missing render method on %s: %s"%( |
| 329 |
repr(self), name)) |
| 330 |
method = method(" ".join(parts[1:])) |
| 331 |
|
| 332 |
else: |
| 333 |
method = template.renderer.get(self, name, None) |
| 334 |
|
| 335 |
if method is None: |
| 336 |
raise Exception("Missing render method on %s: %s"%( |
| 337 |
repr(self), name)) |
| 338 |
|
| 339 |
return method |
| 340 |
|
| 341 |
def lookupDataMethod(self, name): |
| 342 |
"""returns a callable (request, tag) -> something. |
| 343 |
|
| 344 |
If name is a number, this will be tag.slotData[number]. |
| 345 |
If name contains a blank, name will be split, and data_name |
| 346 |
will be called with the parts[1:] as arguments to obtain |
| 347 |
the callable. |
| 348 |
Else this will just return data_name. |
| 349 |
""" |
| 350 |
try: |
| 351 |
ct = int(name) |
| 352 |
def getter(request, tag): |
| 353 |
data = "<unset>" |
| 354 |
try: |
| 355 |
return tag.slotData[ct] |
| 356 |
except Exception as ex: |
| 357 |
raise NoDataError("While trying to get item %s in %s:" |
| 358 |
" %s"%(ct, data, ex)) |
| 359 |
return getter |
| 360 |
except (ValueError, TypeError): |
| 361 |
# it's not a number, so keep trying |
| 362 |
pass |
| 363 |
|
| 364 |
if " " in name: |
| 365 |
parts = name.split() |
| 366 |
return getattr(self, "data_"+parts[0])(" ".join(parts[1:])) |
| 367 |
|
| 368 |
return getattr(self, "data_"+name) |
| 369 |
|
| 370 |
|
| 371 |
class NevowcElement(CommonRenderers, template.Element): |
| 372 |
"""a template.Element that has all our basic renderer functions. |
| 373 |
|
| 374 |
This is probably what you want to base your own elements on. |
| 375 |
""" |
| 376 |
pass |
| 377 |
|
| 378 |
|
| 379 |
def elementFromTag(tag, rendererFactory): |
| 380 |
"""returns a t.w.template element rendering tag but using |
| 381 |
a rendererFactory (a class). |
| 382 |
|
| 383 |
This is used here to furnish the template element with externally defined |
| 384 |
renderers. You probably won't need this outside of testing code, as |
| 385 |
TemplatedPage already arranges everything if you use loader. |
| 386 |
""" |
| 387 |
class _Root(rendererFactory, template.Element): |
| 388 |
def __init__(self, child): |
| 389 |
self.child = child |
| 390 |
|
| 391 |
def render(self, request): |
| 392 |
return self.child |
| 393 |
|
| 394 |
return _Root(tag) |
| 395 |
|
| 396 |
|
| 397 |
class TemplatedPage(resource.Resource, CommonRenderers): |
| 398 |
"""A t.w Resource rendering from its loader attribute. |
| 399 |
|
| 400 |
To actually have the full feature set, be sure to use the XMLFile |
| 401 |
loader from this module as the loader. |
| 402 |
|
| 403 |
It does *not* restore ``renderHTTP`` or ``locateChild``, as there's no |
| 404 |
sane way to keep the interface. Port to t.w-style getChild; if |
| 405 |
you override ``render_GET``, you probably want to end it |
| 406 |
with ``return TemplatedPage.render_GET(self, request)``. |
| 407 |
|
| 408 |
This will look for a ``gavo_useDoctype`` attribute on the |
| 409 |
template and use an XHTML doctype if it's not present. |
| 410 |
|
| 411 |
You can override ``handleError(failure, request)`` to override the |
| 412 |
error document (this will finish the request, too). |
| 413 |
|
| 414 |
If you need extra callbacks, define your own render method and use |
| 415 |
the renderDocument method to obtain a "naked" deferred. |
| 416 |
""" |
| 417 |
loader = None # override in derived classes |
| 418 |
defaultDoctype = ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' |
| 419 |
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">') |
| 420 |
|
| 421 |
def _getDoc(self, request): |
| 422 |
if self.loader is None: |
| 423 |
raise Exception("You must override loader on TemplatedPage") |
| 424 |
|
| 425 |
# define an artificial root element so renderers see the resource's |
| 426 |
# attributes (like render methods or data attributes) |
| 427 |
class _Root(template.Element): |
| 428 |
loader = self.loader |
| 429 |
|
| 430 |
# make the element see our methods and attributes |
| 431 |
def __getattr__(el_self, name): |
| 432 |
if name.startswith("__"): |
| 433 |
raise AttributeError(name) |
| 434 |
return getattr(self, name) |
| 435 |
|
| 436 |
# we need to redirect lookupRenderMethod so Element |
| 437 |
# can deal with render="foo arg". |
| 438 |
def lookupRenderMethod(el_self, *args): |
| 439 |
return self.lookupRenderMethod(*args) |
| 440 |
|
| 441 |
return _Root() |
| 442 |
|
| 443 |
def handleError(self, failure, request): |
| 444 |
failure.printTraceback() |
| 445 |
request.write("Uncaught error:\n<pre><![CDATA[\n{}\n]]></pre>\n" |
| 446 |
.format(failure.getErrorMessage()) |
| 447 |
.encode("utf-8")) |
| 448 |
try: |
| 449 |
request.finish() |
| 450 |
except defer.AlreadyCalledError: |
| 451 |
# I can't say what state I'm in at this state. If the request |
| 452 |
# was already finished nobody saw the message, so at least |
| 453 |
# gargle it out on stderr and hope for the best |
| 454 |
sys.stderr.write("Error on request that was already finished:\n") |
| 455 |
sys.stderr.write(failure.getErrorMessage()) |
| 456 |
pass |
| 457 |
|
| 458 |
def renderDocument(self, request): |
| 459 |
"""returns a deferred firing when the document is written. |
| 460 |
|
| 461 |
Use this method rather than render if you need to introduce |
| 462 |
extra callbacks. |
| 463 |
|
| 464 |
This does *not* finish the request by itself. |
| 465 |
""" |
| 466 |
doc = self._getDoc(request) |
| 467 |
doctype = getattr(doc, "gavo_useDoctype", self.defaultDoctype) |
| 468 |
if isinstance(doctype, str): |
| 469 |
doctype = doctype.encode("utf-8") |
| 470 |
if doctype is not None: |
| 471 |
request.write(doctype) |
| 472 |
request.write(b'\n') |
| 473 |
return template.flatten(request, doc, request.write) |
| 474 |
|
| 475 |
def finishRequest(self, ignored, request): |
| 476 |
request.finish() |
| 477 |
|
| 478 |
def render_GET(self, request): |
| 479 |
self.renderDocument(request |
| 480 |
).addCallback(self.finishRequest, request |
| 481 |
).addErrback(self.handleError, request) |
| 482 |
return server.NOT_DONE_YET |
| 483 |
|
| 484 |
# default: handle GET and POST equivalently, don't |
| 485 |
# care about HEAD (should we?) |
| 486 |
render_POST = render_GET |
| 487 |
|
| 488 |
def getChild(self, name, request): |
| 489 |
if not name and not request.postpath: |
| 490 |
return self |
| 491 |
return resource.NoResource() |
| 492 |
|
| 493 |
|
| 494 |
class Redirect(resource.Resource): |
| 495 |
# todo: Anyone using this? Why not t.w.util.Redirect? |
| 496 |
def __init__(self, destURL, code=302): |
| 497 |
self.destURL = str(destURL) |
| 498 |
self.code = 302 |
| 499 |
|
| 500 |
def render(self, request): |
| 501 |
# todo: see if destURL is relative and fix based on request? |
| 502 |
request.setHeader("location", self.destURL) |
| 503 |
request.setResponseCode(self.code) |
| 504 |
request.setHeader("Content-Type", "text/plain") |
| 505 |
return ("You are not supposed to see this, but if you do:" |
| 506 |
" Your browser was supposed to go to %s"%self.destURL) |
| 507 |
|
| 508 |
|
| 509 |
def flattenSync(element, request=None): |
| 510 |
"""returns a string representation of element synchronously. |
| 511 |
|
| 512 |
This, of course, only works if there are no deferreds within element. |
| 513 |
""" |
| 514 |
result = [flattenSync] |
| 515 |
def _(res): |
| 516 |
result[0] = res |
| 517 |
|
| 518 |
template.flattenString(request, element).addBoth(_) |
| 519 |
result = result[0] |
| 520 |
|
| 521 |
if result is flattenSync: |
| 522 |
raise NotImplementedError("flattenSync cannot deal with elements" |
| 523 |
" containing deferreds.") |
| 524 |
elif hasattr(result, "raiseException"): |
| 525 |
result.raiseException() |
| 526 |
|
| 527 |
return result |
| 528 |
|
| 529 |
|
| 530 |
def flattenSyncToString(element, request=None): |
| 531 |
"""returns elemented flattened to a string (as opposed to bytes) |
| 532 |
""" |
| 533 |
return flattenSync(element, request).decode("utf-8") |
| 534 |
|
| 535 |
# vim:et:sta:sw=4 |