| 1 |
""" |
| 2 |
The renderer for VOSI examples, plus the docutils extensions provided for |
| 3 |
them. |
| 4 |
|
| 5 |
If you have a renderer that needs custom text roles or directives, read the |
| 6 |
docstring of misctricks.RSTExtensions and add whatever roles you need below, |
| 7 |
more or less like this:: |
| 8 |
|
| 9 |
misctricks.RSTExtensions.makeTextRole("niceRole") |
| 10 |
|
| 11 |
Only go through RSTExtensions, as these will make sure HTML postprocessing |
| 12 |
happens as required. |
| 13 |
|
| 14 |
The reason we keep the roles here and not in the renderer modules where they'd |
| 15 |
logically belong (and where they should be documented in the renderer |
| 16 |
docstrings) is that we don't want docutils imports all over the place. |
| 17 |
""" |
| 18 |
|
| 19 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 20 |
#c |
| 21 |
#c This program is free software, covered by the GNU GPL. See the |
| 22 |
#c COPYING file in the source distribution. |
| 23 |
|
| 24 |
|
| 25 |
import re |
| 26 |
|
| 27 |
from docutils import nodes |
| 28 |
from docutils import utils as rstutils |
| 29 |
from docutils.parsers import rst |
| 30 |
|
| 31 |
from lxml import etree |
| 32 |
|
| 33 |
from twisted.web import template |
| 34 |
from gavo import utils |
| 35 |
from gavo.utils import misctricks |
| 36 |
from gavo import base |
| 37 |
from gavo import svcs |
| 38 |
from gavo.web import grend |
| 39 |
|
| 40 |
|
| 41 |
class Example(base.MetaMixin): |
| 42 |
"""A formatted example. |
| 43 |
|
| 44 |
These get constructed with example meta items and glue these |
| 45 |
together with the nevow rendering system. |
| 46 |
|
| 47 |
An important role of this is the translation from the HTML class |
| 48 |
attribute values we use in ReStructuredText to the RDFa properties |
| 49 |
in the output. The first class that has a matching property wins. |
| 50 |
|
| 51 |
There's the special exmeta render function that works like metahtml, |
| 52 |
except it's using the example's meta. |
| 53 |
""" |
| 54 |
def __init__(self, exMeta): |
| 55 |
base.MetaMixin.__init__(self) |
| 56 |
self.setMetaParent(exMeta) |
| 57 |
self.original = exMeta |
| 58 |
self.title = base.getMetaText(self.original, "title", propagate=False) |
| 59 |
self.htmlId = re.sub(r"\W", "", self.title) |
| 60 |
|
| 61 |
def _getParsed(self): |
| 62 |
"""returns an etree dom for an XHTML rendering of this example. |
| 63 |
""" |
| 64 |
rawHTML = self.original.getContent("html") |
| 65 |
return etree.fromstring( |
| 66 |
'<div typeof="example" id="%s" resource="#%s">\n' |
| 67 |
'<h2 property="name">%s</h2>\n' |
| 68 |
'%s\n</div>'%( |
| 69 |
self.htmlId, |
| 70 |
self.htmlId, |
| 71 |
utils.escapePCDATA(self.title), |
| 72 |
rawHTML)) |
| 73 |
|
| 74 |
def _getTranslatedHTML(self): |
| 75 |
parsed = self._getParsed() |
| 76 |
actOnClasses = set(misctricks.RSTExtensions.classToProperty) |
| 77 |
|
| 78 |
for node in parsed.iterfind(".//*[@class]"): |
| 79 |
nodeClasses = set(node.attrib["class"].split()) |
| 80 |
properties = " ".join(misctricks.RSTExtensions.classToProperty[c] |
| 81 |
for c in actOnClasses & nodeClasses) |
| 82 |
if properties: |
| 83 |
node.set("property", properties) |
| 84 |
|
| 85 |
# For now, I assume element content always is intended to |
| 86 |
# be the relation object (rather than a href that might |
| 87 |
# be present and would take predence by RDFa |
| 88 |
if "href" in node.attrib or "src" in node.attrib: |
| 89 |
node.set("content", node.text) |
| 90 |
|
| 91 |
return etree.tostring(parsed, encoding="utf-8") |
| 92 |
|
| 93 |
def getTAPQuery(self): |
| 94 |
parsed = self._getParsed() |
| 95 |
# if there are multiple example queries (there shouldn't) we |
| 96 |
# are happy with the first |
| 97 |
for node in parsed.iterfind( |
| 98 |
".//*[@class='dachs-ex-tapquery literal-block']"): |
| 99 |
return node.text |
| 100 |
raise ValueError("No TAP query in here") |
| 101 |
|
| 102 |
|
| 103 |
class Examples(grend.CustomTemplateMixin, grend.ServiceBasedPage): |
| 104 |
r"""A renderer for examples for service usage. |
| 105 |
|
| 106 |
This renderer formats _example meta items in its service. Its output |
| 107 |
is XHTML compliant to VOSI examples; clients can parse it to, |
| 108 |
for instance, fill forms for service operation or display examples |
| 109 |
to users. |
| 110 |
|
| 111 |
The examples make use of RDFa to convey semantic markup. To see |
| 112 |
what kind of semantics is contained, try |
| 113 |
http://www.w3.org/2012/pyRdfa/Overview.html and feed it the |
| 114 |
example URL of your service. |
| 115 |
|
| 116 |
The default content of _example is ReStructuredText, and, really, not much |
| 117 |
else makes sense. An example for such a meta item can be viewed by |
| 118 |
executing ``gavo admin dumpDF //userconfig``, in the tapexamples STREAM. |
| 119 |
|
| 120 |
To support annotation of things within the example text, DaCHS |
| 121 |
defines several RST extensions, both interpreted text roles (used like |
| 122 |
``:role-name:`content with blanks```) and custom directives (used |
| 123 |
to mark up blocks introduced by a single line like |
| 124 |
``.. directive-name ::`` (the blanks before and after the |
| 125 |
directive name are significant). |
| 126 |
|
| 127 |
Here's the custom interpreted text roles: |
| 128 |
|
| 129 |
* *dl-id*: An publisher DID a service returns data for (used in |
| 130 |
datalink examples) |
| 131 |
* *taptable*: A (fully qualified) table name a TAP example query is |
| 132 |
(particularly) relevant for; in HTML, this is also a link |
| 133 |
to the table description. |
| 134 |
* *genparam*: A "generic parameter" as defined by DALI. The values |
| 135 |
of these have the form param(value), e.g., :genparam:\`POS(32,4)\`. |
| 136 |
Right now, not parentheses are allowed in the value. Complain |
| 137 |
if this bites you. |
| 138 |
|
| 139 |
These are the custom directives: |
| 140 |
|
| 141 |
* *tapquery*: The query discussed in a TAP example. |
| 142 |
|
| 143 |
Examples for how to write TAP examples are in the userconfig.rd |
| 144 |
distributed with DaCHS. Examples for Datalink examples can |
| 145 |
be found in the GAVO RDs feros/q and califa/q3.A |
| 146 |
|
| 147 |
In addition, you can define moreExamples meta items. These point to |
| 148 |
further DALI-compliant examples document(s) and will typically be |
| 149 |
presented in a hierarchical fashion by clients. The content is |
| 150 |
either a URI to the examples document (when it starts with https?://) |
| 151 |
or a DaCHS-internal reference to a service with the examples. They |
| 152 |
should have a (short) title meta child to give clients a hint as to |
| 153 |
what the continuation is about, somewhat like this:: |
| 154 |
|
| 155 |
<meta> |
| 156 |
# more examples provided by the ex service in the RD rr/q |
| 157 |
moreExamples: rr/q#ex |
| 158 |
moreExamples.title: RegTAP |
| 159 |
# more examples provided by an external document |
| 160 |
moreExamples: http://ivoa.net/doc/obscore/tap-examples.xhtml |
| 161 |
moreExamples.title: ObsCore |
| 162 |
</meta> |
| 163 |
""" |
| 164 |
name = "examples" |
| 165 |
checkedRenderer = False |
| 166 |
customTemplate = svcs.loadSystemTemplate("examples.html") |
| 167 |
gavo_useDoctype = (b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN"' |
| 168 |
b' "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">') |
| 169 |
|
| 170 |
def render(self, request): |
| 171 |
# overridden to return a 404 when there are no examples, |
| 172 |
# which is what TOPCAT wants. |
| 173 |
self.serviceExamples = list( |
| 174 |
self.service.iterMeta("_example")) |
| 175 |
if not self.serviceExamples: |
| 176 |
request.setResponseCode(404) |
| 177 |
return grend.ServiceBasedPage.render(self, request) |
| 178 |
|
| 179 |
@classmethod |
| 180 |
def isCacheable(self, segments, request): |
| 181 |
return True |
| 182 |
|
| 183 |
@classmethod |
| 184 |
def isBrowseable(cls, service): |
| 185 |
return True |
| 186 |
|
| 187 |
@template.renderer |
| 188 |
def title(self, request, tag): |
| 189 |
return tag["Examples for %s"%base.getMetaText( |
| 190 |
self.service, "title")] |
| 191 |
|
| 192 |
@template.renderer |
| 193 |
def noexamples(self, request, tag): |
| 194 |
if not self.serviceExamples: |
| 195 |
return tag |
| 196 |
return "" |
| 197 |
|
| 198 |
def data_continuations(self, request, tag): |
| 199 |
"""yields dicts with title and uri keys from this service's |
| 200 |
continuation metadata. |
| 201 |
""" |
| 202 |
for item in self.service.iterMeta("moreExamples"): |
| 203 |
src = item.getContent(targetFormat="text") |
| 204 |
if not re.match("https?://", src): |
| 205 |
svc = base.resolveId(self.rd, src, forceType=svcs.Service) |
| 206 |
src = svc.getURL("examples") |
| 207 |
|
| 208 |
yield { |
| 209 |
"uri": src, |
| 210 |
"title": str(item.getMeta("title", default="More"))} |
| 211 |
|
| 212 |
def data_examples(self, request, tag): |
| 213 |
"""returns Example instances from the service metadata. |
| 214 |
""" |
| 215 |
for ex in self.serviceExamples: |
| 216 |
yield Example(ex) |
| 217 |
|
| 218 |
def data_rendered(self, request, tag): |
| 219 |
"""returns the current data (an example) as XHTML. |
| 220 |
""" |
| 221 |
data = tag.slotData |
| 222 |
if not hasattr(data, "renderedDescription"): |
| 223 |
data.renderedDescription = data._getTranslatedHTML() |
| 224 |
return data.renderedDescription |
| 225 |
|
| 226 |
def data_id(self, request, tag): |
| 227 |
"""returns the htmlId attribute of the current data (an example). |
| 228 |
""" |
| 229 |
return tag.slotData.htmlId |
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
################## RST extensions |
| 234 |
# When you add anything here, be sure to update the Examples docstring |
| 235 |
# above. |
| 236 |
|
| 237 |
|
| 238 |
### ...for TAP |
| 239 |
|
| 240 |
def _taptableRoleFunc(name, rawText, text, lineno, inliner, |
| 241 |
options={}, content=[]): |
| 242 |
tablename = nodes.emphasis(rawText, text) |
| 243 |
tablename["classes"] = ["dachs-ex-taptable"] |
| 244 |
descr = nodes.reference("\u2197", "\u2197", |
| 245 |
refuri="/tableinfo/%s"%text) |
| 246 |
descr["classes"] = ["taptable-link"] |
| 247 |
return [descr, tablename], [] |
| 248 |
|
| 249 |
misctricks.RSTExtensions.makeTextRole("taptable", _taptableRoleFunc, |
| 250 |
propertyName="table") |
| 251 |
del _taptableRoleFunc |
| 252 |
|
| 253 |
class _TAPQuery(rst.Directive): |
| 254 |
has_content = True |
| 255 |
|
| 256 |
def run(self): |
| 257 |
body = "\n".join(self.content) |
| 258 |
res = nodes.literal_block(body, body) |
| 259 |
res["classes"] = ["dachs-ex-tapquery"] |
| 260 |
return [res] |
| 261 |
|
| 262 |
misctricks.RSTExtensions.addDirective("tapquery", _TAPQuery, |
| 263 |
propertyName="query") |
| 264 |
del _TAPQuery |
| 265 |
|
| 266 |
|
| 267 |
### ...for datalink |
| 268 |
|
| 269 |
misctricks.RSTExtensions.makeTextRole("dl-id") |
| 270 |
|
| 271 |
### ...for DALI-style generic parameters |
| 272 |
|
| 273 |
def _genparamRoleFunc(name, rawText, text, lineno, inliner, |
| 274 |
options={}, content=[]): |
| 275 |
mat = re.match(r"([^(]+)\(([^)]*)\)$", text) |
| 276 |
if not mat: |
| 277 |
msg = inliner.reporter.error( |
| 278 |
"genparam content must have the form key(value); %s does not."%text) |
| 279 |
return [inliner.problematic(rawText, rawText, msg)], [msg] |
| 280 |
|
| 281 |
key, value = mat.groups() |
| 282 |
|
| 283 |
formatted = """<span property="generic-parameter" typeof="keyval" |
| 284 |
class="generic-parameter"> |
| 285 |
<span property="key" class="genparam-key">%s</span> = |
| 286 |
<span property="value" class="genparam-value">%s</span> |
| 287 |
</span>"""%( |
| 288 |
utils.escapePCDATA(rstutils.unescape(key, 1)), |
| 289 |
utils.escapePCDATA(rstutils.unescape(value, 1))) |
| 290 |
res = nodes.raw( |
| 291 |
rawsource=rawText, |
| 292 |
text=formatted, |
| 293 |
format='html') |
| 294 |
return [res], [] |
| 295 |
|
| 296 |
misctricks.RSTExtensions.makeTextRole("genparam", _genparamRoleFunc) |
| 297 |
del _genparamRoleFunc |
| 298 |
|