Debian Codegraph @

gavo/web/grend.py

raw
1 """
2 Basic Code for Renderers.
3
4 Renderers are frontends for services. They provide the glue to
5 somehow acquire input (typically, nevow contexts) and then format
6 the result for the user.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import functools
16 import types
17 import os
18 import urllib.parse
19
20 from twisted.internet import threads
21 from twisted.python import log
22 from twisted.python import urlpath
23 from twisted.web import template
24 from twisted.web.template import tags as T
25
26 from gavo import base
27 from gavo import svcs
28 from gavo import rsc
29 from gavo import utils
30 from gavo.base import meta
31 from gavo.base import typedmeta
32 from gavo.formal import nevowc
33 from gavo.protocols import creds
34 from gavo.protocols import vocabularies
35 from gavo.svcs import weberrors
36 from gavo.web import common
37 from gavo.web import htmltable
38
39
40 __docformat__ = "restructuredtext en"
41
42
43 @functools.cache
44 def getRelationshipTypes():
45 try:
46 return vocabularies.get_vocabulary("voresource/relationship_type")
47 except base.ReportableError:
48 # that's from get_vocabulary
49 return {"terms": {}}
50
51
52 class RDBlocked(Exception):
53 """is raised when a ResourceDescriptor is blocked due to maintenance
54 and caught by the root resource..
55 """
56
57
58 ########## Useful mixins for Renderers
59
60 class GavoRenderMixin(common.CommonRenderers):
61 """A mixin with renderers useful throughout the data center.
62
63 Rendering of meta information:
64
65 * <tag n:render="meta">METAKEY</tag> or
66 * <tag n:render="metahtml">METAKEY</tag>
67
68 Rendering the sidebar --
69 <body n:render="withsidebar">. This will only work if the renderer
70 has a service attribute that's enough of a service (i.e., carries meta
71 and knows how to generate URLs).
72
73 Conditional rendering:
74
75 * ifmeta
76 * imownmeta
77 * ifdata
78 * ifnodata
79 * ifslot
80 * ifnoslot
81 * ifadmin
82
83 Obtaining system info
84
85 * rd <rdId> -- makes the referenced RD the current data (this is
86 not too useful right now, but it lets you check of the existence
87 of RDs already)
88
89 Other:
90
91 * dcRelations -- sets the current data to a dictionary of DataCite
92 relationships of the current resource. That's probably only
93 interesting in the default sidebar.
94 """
95 _sidebar = svcs.loadSystemTemplate("sidebar.html").load()
96 _footer = svcs.loadSystemTemplate("footer.html").load()
97
98 # macro package to use when expanding macros. Just set this
99 # in the constructor as necessary (ServiceBasedRenderer has the
100 # service here)
101 macroPackage = None
102
103 def _initGavoRender(self):
104 # call this to initialize this mixin.
105 # (kept for backward compatibility; don't use this any more)
106 pass
107
108 def _doRenderMeta(self, request, tag, raiseOnFail=False, plain=False,
109 carrier=None):
110 if carrier is None:
111 carrier = self.metaCarrier
112 if not hasattr(carrier, "_metaRenderCache"):
113 carrier._metaRenderCache = {}
114
115 metaKey = "(inaccessible)"
116 try:
117 for child in tag.children:
118 if isinstance(child, str) and child.strip():
119 metaKey = child.strip()
120 break
121
122 if (metaKey, plain) in carrier._metaRenderCache:
123 rendered = carrier._metaRenderCache[(metaKey, plain)]
124
125 else:
126 htmlBuilder = common.HTMLMetaBuilder(self.macroPackage)
127
128 if plain:
129 rendered = base.getMetaText(carrier, metaKey, raiseOnFail=True,
130 macroPackage=self.macroPackage)
131
132 else:
133 rendered = carrier.buildRepr(metaKey, htmlBuilder, raiseOnFail=True)
134
135 carrier._metaRenderCache[(metaKey, plain)] = rendered
136
137 except base.NoMetaKey:
138 if raiseOnFail:
139 raise
140 return template.Comment("Meta item %s not given."%metaKey)
141 except Exception as ex:
142 msg = "Meta %s bad (%s)"%(metaKey, str(ex))
143 base.ui.notifyError(msg)
144 return template.Comment(msg)
145
146 tag.clear()
147 return tag[rendered]
148
149 def data_meta(self, metaKey):
150 """returns the value for the meta key metaName on this service.
151 """
152 def get(request, data):
153 return self.metaCarrier.getMeta(metaKey)
154 return get
155
156 @template.renderer
157 def meta(self, request, tag):
158 """replaces a meta key with a plain text rendering of the metadata
159 in the service.
160 """
161 return self._doRenderMeta(request, tag, plain=True)
162
163 @template.renderer
164 def metahtml(self, request, tag):
165 """replaces a meta key with an html rendering of the metadata in
166 the service.
167 """
168 return self._doRenderMeta(request, tag)
169
170 @template.renderer
171 def datameta(self, request, tag):
172 """replaces the meta key in the contents with the corresponding
173 meta key's HTML rendering.
174 """
175 return self._doRenderMeta(request, tag, carrier=tag.slotData)
176
177 @template.renderer
178 def ifmeta(self, metaName, propagate=True):
179 """renders its children if there is metadata for metaName.
180 """
181 if propagate:
182 hasMeta = self.metaCarrier.getMeta(metaName) is not None
183 else:
184 hasMeta = self.metaCarrier.getMeta(metaName, propagate=False) is not None
185
186 if hasMeta:
187 return lambda request, tag: tag
188 else:
189 return lambda request, tag: ""
190
191 @template.renderer
192 def ifownmeta(self, metaName):
193 """renders its children if there is metadata for metaName in
194 the service itself.
195 """
196 return self.ifmeta(metaName, propagate=False)
197
198 @template.renderer
199 def ifdata(self, request, tag):
200 if tag.slotData:
201 return tag
202 else:
203 return ""
204
205 @template.renderer
206 def ifnodata(self, request, tag):
207 if not tag.slotData:
208 return tag
209 else:
210 return ""
211
212 @template.renderer
213 def ifslot(self, slotName, invert=False):
214 """renders the children for slotName is present an true in a boolean
215 sense in the current data (which must be a dictionary).
216 """
217 def render(request, tag):
218 if invert:
219 returnTag = not tag.slotData.get(slotName)
220 else:
221 returnTag = not not tag.slotData.get(slotName)
222
223 try:
224 if returnTag:
225 return tag
226 else:
227 return ""
228 except KeyError:
229 return ""
230 return render
231
232 @template.renderer
233 def ifnoslot(self, slotName):
234 """renders if slotName is missing or not true in the current data
235 (which must be a dictionary).
236 """
237 return self.ifslot(slotName, invert=True)
238
239 @template.renderer
240 def ifadmin(self, request, tag):
241 # NOTE: use of this renderer is *not* enough to protect critical operations
242 # since it does not check if the credentials are actually provided.
243 # Use this only hide links that will give 403s (or somesuch) for
244 # non-admins anyway (and the like).
245 if request.getUser()=="gavoadmin":
246 return tag
247 else:
248 return ""
249
250 @template.renderer
251 def explodableMeta(self, request, tag):
252 metaKey = tag.children[0]
253 title = tag.attributes.get("title", metaKey.capitalize())
254 try:
255 return T.div(class_="explodable")[
256 T.h4(class_="exploHead")[title],
257 T.div(class_="exploBody")[
258 self._doRenderMeta(request, tag, raiseOnFail=True)]]
259 except base.MetaError:
260 return ""
261
262 @template.renderer
263 def intro(self, request, tag):
264 """returns something suitable for inclusion above the form.
265
266 The renderer tries, in sequence, to retrieve a meta called _intro,
267 the description meta, or nothing.
268 """
269 for key in ["_intro", "description"]:
270 if self.service.getMeta(key, default=None) is not None:
271 introKey = key
272 break
273 else:
274 introKey = None
275 if introKey is None:
276 return tag[""]
277 else:
278 return tag[self.metaCarrier.buildRepr(introKey,
279 common.HTMLMetaBuilder(self.macroPackage),
280 raiseOnFail=False)]
281
282 @template.renderer
283 def authinfo(self, request, tag):
284 svc = getattr(self, "service", None)
285
286 if svc and request.getUser() and request.getAuthUser():
287 anchorText = "Log out %s"%(utils.debytify(request.getAuthUser()))
288 targetURL = "/login?relog=True"
289 explanation = " (give an empty user name in the dialog popping up)"
290 else:
291 targetURL = urlpath.URLPath.fromString("/login")
292 targetURL.query = "nextURL=%s"%urllib.parse.quote(request.uri)
293 anchorText = "Log in"
294 explanation = ""
295
296 return tag[T.a(href=str(targetURL))[
297 anchorText], explanation]
298
299 @template.renderer
300 def prependsite(self, request, tag):
301 """prepends a site id to the body.
302
303 This is intended for titles and similar; it puts the string in
304 [web]sitename in front of anything that already is in tag.
305 """
306 tag.children = [base.getConfig("web", "sitename")]+tag.children
307 return tag
308
309 @template.renderer
310 def withsidebar(self, request, tag):
311 oldChildren = tag.children
312 tag.children = []
313 return tag(class_="container")[
314 self._sidebar,
315 T.div(id="body")[
316 oldChildren,
317 self._footer,
318 ],
319 ]
320
321 def data_rd(self, rdId):
322 """returns the RD referenced in the body (or None if the RD is not there)
323 """
324 def _(request, tag):
325 try:
326 return base.caches.getRD(rdId)
327 except base.NotFoundError:
328 return None
329 return _
330
331 def data_dcRelations(self, request, tag):
332 """makes [{anchor, href, relname}] for the datacite relationships
333 of the current data.
334 """
335 relationships = []
336
337 metaCarrier = self.rd
338 # for now, we *only* use relationships on the main RD. If we
339 # ever want to make this overridable in individual services,
340 # se if there's a service attribute and use that as a metaCarrier
341 # if available. And then do away with the direct checks in
342 # meta_ below and use normal iterMeta(., propagate=True)
343 if self.macroPackage:
344 expand = self.macroPackage.expand
345 else:
346 expand = lambda v: v
347
348 # I'm peeking directly into meta_ here because the loop is
349 # actually executed quite a number of time and there is no
350 # reason for parsing the keys here anyway.
351 for key in meta.getKeysForClass(typedmeta.RelatedResourceMeta):
352 if key in metaCarrier.meta_:
353 for m in metaCarrier.iterMeta(key):
354 key = key[0].upper()+key[1:]
355 try:
356 relationships.append({
357 "relname": getRelationshipTypes()["terms"
358 ].get(key, {"label": key})["label"],
359 "anchor": expand(m.getContent()),
360 "href": expand(base.makeLinkForIvoid(str(m.getMeta("ivoId"))))})
361 except ValueError:
362 # presumably can't make a link from ivoId
363 pass
364
365 return relationships
366
367
368 class HTMLResultRenderMixin(object):
369 """is a mixin with render functions for HTML tables and associated
370 metadata within other pages.
371
372 This is primarily used for the Form renderer; it expects to see
373 the service's result in a result attribute.
374
375 The thing mixing this in at least has to have self.queryData.
376 """
377 result = None
378
379 def _getCurrentData(self, request, tag):
380 """helps resulttable and resultline in figuring out the data to render.
381
382 See resulttable for the rought rules.
383 """
384 try:
385 data = tag.slotData
386 except nevowc.NoDataError:
387 data = None
388 else:
389 if not isinstance(data, rsc.BaseTable):
390 data = None
391
392 if data is None:
393 data = getattr(self, "result", None)
394
395 if isinstance(data, rsc.BaseTable):
396 return data
397
398 if hasattr(data, "getPrimaryTable"):
399 return data.getPrimaryTable()
400
401 return None
402
403 @template.renderer
404 def resulttable(self, request, tag):
405 """HTML-renders a table.
406
407 If the current data is a table instance, that's what's used. Else,
408 it falls back to the result attribute of the current object.
409 """
410 data = self._getCurrentData(request, tag)
411 if data is None:
412 # we're probably handling Form errors
413 return ""
414
415 return htmltable.HTMLTableFragment(data, self.queryMeta)
416
417 @template.renderer
418 def resultline(self, request, tag):
419 """HTML-renders a single table line (the first of the result, actually.
420 """
421 data = self._getCurrentData(request, tag)
422 if data is None:
423 # we're probably handling Form errors
424 return ""
425
426 return htmltable.HTMLKeyValueFragment(data, self.queryMeta)
427
428 @template.renderer
429 def parpair(self, request, tag):
430 data = tag.slotData
431 if data is None or data[1] is None or "__" in data[0]:
432 return ""
433 return tag["%s: %s"%data]
434
435 @template.renderer
436 def ifresult(self, request, tag):
437 if self.queryMeta.get("Matched", 1)!=0:
438 return tag
439 else:
440 return ""
441
442 @template.renderer
443 def ifnoresult(self, request, tag):
444 if self.queryMeta.get("Matched", 1)==0:
445 return tag
446 else:
447 return ""
448
449 @template.renderer
450 def iflinkable(self, request, tag):
451 """renders tag if we have a linkable result, nothing otherwise.
452
453 Linkable means that the result will come out as displayed through
454 a link. Currently, we only see if a file upload was part of
455 the result production -- if there was, it's not linkable.
456
457 This currently doesn't even look if a file was indeed passed in: Things
458 already are not linkable if the service takes a file upload, whether
459 that's used or not.
460 """
461 for ik in self.service.getInputKeysFor(self):
462 if ik.type=='file':
463 return ""
464 return tag
465
466 @template.renderer
467 def servicestyle(self, request, tag):
468 """enters custom service styles into tag.
469
470 They are taken from the service's customCSS property.
471 """
472 if self.service and self.service.getProperty("customCSS", False):
473 return tag[self.service.getProperty("customCSS")]
474 return ""
475
476 def data_result(self, request, tag):
477 return self.result
478
479 def data_rows(self, request, tag):
480 """returns the rows of the primary result table.
481 """
482 return self.result.getPrimaryTable().rows
483
484 def _makeParPair(self, key, value, fieldDict):
485 title = key
486 if key in fieldDict:
487 title = fieldDict[key].getLabel()
488 if fieldDict[key].type=="file":
489 value = "File upload '%s'"%value[0]
490 else:
491 value = str(value)
492 return title, value
493
494 __suppressedParNames = set(["submit"])
495
496 def data_queryseq(self, request, tag):
497 if not self.result:
498 return []
499
500 if self.service:
501 fieldDict = dict((f.name, f)
502 for f in self.service.getInputKeysFor(self))
503 else:
504 fieldDict = {}
505
506 s = [self._makeParPair(k, v, fieldDict)
507 for k, v in self.queryMeta.get("formal_data", {}).items()
508 if v is not None and v!=[]
509 and k not in self.__suppressedParNames
510 and not k.startswith("_")]
511 s.sort()
512 return s
513
514 @template.renderer
515 def flotplot(self, request, tag):
516 """adds an onClick attribute opening a flot plot.
517
518 This is evaluates the _plotOptions meta. This should be a javascript
519 dictionary literal with certain plot options. More on this in
520 the reference documentation on the _plotOptions meta.
521 """
522 plotOptions = base.getMetaText(self.service, "_plotOptions")
523 if plotOptions is not None:
524 args = ", %s"%plotOptions
525 else:
526 args = ""
527 return tag(onclick="openFlotPlot($('table.results')%s)"%args)
528
529 @template.renderer
530 def param(self, format):
531 """returns the value of the parameter named content formatted as a python
532 string.
533
534 Undefined params and NULLs give N/A. Data needs to be something that
535 has a getParam method.
536 """
537 def renderer(request, tag):
538 parName = tag.children[0].strip()
539 tag.clear()
540 try:
541 val = tag.slotData.getParam(parName)
542 if val is None:
543 return tag["N/A"]
544
545 return tag[format%val]
546 except base.NotFoundError:
547 return tag["N/A"]
548 return renderer
549
550
551 class CustomTemplateMixin(object):
552 """a mixin providing for customized templates.
553
554 This works by making loader a property first checking if
555 the instance has a customTemplate attribute evaluating to true.
556 If it has and it is referring to a string, its content is used
557 as a resdir-relative path to a nevow XML template. If it has and
558 it is not a string, it will be used as a template directly
559 (it's already "loaded"), else defaultLoader attribute of
560 the instance is used.
561 """
562 customTemplate = None
563
564 def getLoader(self):
565 if not self.customTemplate:
566 return self.defaultLoader
567 elif isinstance(self.customTemplate, str):
568 tplPath = self.rd.getAbsPath(self.customTemplate)
569 if not os.path.exists(tplPath):
570 return self.defaultLoader
571 return nevowc.XMLFile(tplPath)
572 else:
573 return self.customTemplate
574
575 loader = property(getLoader)
576
577
578
579 ############# nevow Resource derivatives used here.
580
581
582 class GavoPage(nevowc.TemplatedPage, GavoRenderMixin):
583 """a base class for all "pages" (i.e. things talking to the web,
584 based on RDs, and possibly using nevow templates) within DaCHS.
585 """
586 def handleError(self, failure, request):
587 weberrors.renderDCErrorPage(failure, request)
588
589
590 class ResourceBasedPage(GavoPage):
591 """A base for renderers based on RDs.
592
593 It is constructed with the resource descriptor and leaves it
594 in the rd attribute.
595
596 The preferredMethod attribute is used for generation of registry records
597 and currently should be either GET or POST. urlUse should be one
598 of full, base, post, or dir, in accord with VOResource.
599
600 Renderers with fixed result types should fill out resultType.
601
602 The makeAccessURL class method is called by service.getURL; it
603 receives the service's base URL and must return a mogrified string
604 that corresponds to an endpoint this renderer will operate on (this
605 could be used to make a Form renderer into a ParamHTTP interface by
606 attaching ?__nevow_form__=genForm&, and the soap renderer does
607 nontrivial things there).
608
609 Renderers capable of producing multiple output formats should
610 give a format key (suitable for formats.getKeyFor) in defaultOutputFormat.
611
612 Within DaCHS, this class is mainly used as a base for ServiceBasedRenderer,
613 since almost always only services talk to the world. However,
614 we try to fudge render and data functions such that the sidebar works.
615 """
616 preferredMethod = "GET"
617 urlUse = "full"
618 resultType = None
619 defaultOutputFormat = "votable"
620 # parameterStyle is a hint for inputKeys how to transform themselves
621 # "clear" keeps types, "form" gives vizier-like expressions
622 # "vo" gives parameter-like expressions.
623 parameterStyle = "clear"
624 name = None
625 aliases = frozenset()
626
627 def __init__(self, request, rd):
628 nevowc.TemplatedPage.__init__(self)
629 self.queryMeta = svcs.QueryMeta.fromRequest(request)
630 self.rd = rd
631 self.metaCarrier = rd
632 self.macroPackage = rd
633 if hasattr(self.rd, "currently_blocked"):
634 raise RDBlocked()
635 self._initGavoRender()
636
637 @classmethod
638 def isBrowseable(self, service):
639 """returns True if this renderer applied to service is usable using a
640 plain web browser.
641 """
642 return False
643
644 @classmethod
645 def isCacheable(self, segments, request):
646 """should return true if the content rendered will only change
647 when the associated RD changes.
648
649 request is a nevow request object. web.root.ArchiveService already
650 makes sure that you only see GET request without arguments and
651 without a user, so you do not need to check this.
652 """
653 return False
654
655 @classmethod
656 def makeAccessURL(cls, baseURL):
657 """returns an accessURL for a service with baseURL to this renderer.
658 """
659 return "%s/%s"%(baseURL, cls.name)
660
661 def data_rdId(self, request, tag):
662 return self.rd.sourceId
663
664 def data_serviceURL(self, type):
665 # for RD's that's simply the rdinfo.
666 return (lambda request, tag:
667 base.makeSitePath("/browse/%s"%self.rd.sourceId))
668
669
670 _IGNORED_KEYS = set(["__nevow_form__", "_charset_", "submit", "nextURL"])
671
672 def _formatRequestArgs(args):
673 r"""formats web.Request.strargs for logging.
674
675 Basically, long objects (ones with len, and len>100) are truncated.
676
677 >>> _formatRequestArgs({"x": range(2), "y": [u"\u3020"], "submit": ["Ok"]})
678 "{'x': [0,1,],'y': ['?',],}"
679 >>> _formatRequestArgs({"hokus": ["Pokus"*300]})
680 "{'hokus': [<data starting with 'PokusPokusPokusPokusPokusPoku>,],}"
681 >>> _formatRequestArgs({"no": []})
682 '{}'
683 >>> _formatRequestArgs({"plönk": ["göschönkt"]})
684 "{'plönk': ['g?sch?nkt',],}"
685 """
686 res = ["{"]
687 for key in sorted(args):
688 valList = args[key]
689 if not valList or key in _IGNORED_KEYS:
690 continue
691 res.append("%s: ["%repr(key))
692 for value in valList:
693 value = repr(value).encode("ascii", "replace").decode("ascii")
694 try:
695 if len(value)>100:
696 res.append("<data starting with %s>,"%value[:30])
697 else:
698 res.append(value+",")
699 except TypeError: # no len on value
700 res.append(repr(value)+",")
701 res.append("],")
702 res.append("}")
703 return "".join(res)
704
705
706 class ServiceBasedPage(ResourceBasedPage):
707 """the base class for renderers turning service-based info into
708 character streams.
709
710 You will need to provide some way to give nevowc.TemplatedPage templates,
711 either by supplying a loader or (usually preferably) mixing in
712 CustomTemplateMixin -- or just override renderHTTP to make do
713 without templates.
714
715 You can set an attribute checkedRenderer=False for renderers that
716 are "generic" and do not need to be enumerated in the allowed
717 attribute of the underlying service ("meta renderers").
718
719 You can set a class attribute openRenderer=True to make a renderer
720 work even on restricted services (which may make sense for stuff like
721 metadata inspection).
722
723 This class overrides t.w.template's renderer so renderers defined
724 in the service (e.g., via an RD) are found, too.
725 """
726
727 checkedRenderer = True
728 openRenderer = False
729
730 def __init__(self, request, service):
731 ResourceBasedPage.__init__(self, request, service.rd)
732
733 if service.hasMeta("superseded"):
734 raise svcs.UnknownURI("This service is superseded by something else.",
735 htmlMessage=T.xml(service.getMeta("superseded").getContent("html")))
736
737 self.service = service
738 if not self.openRenderer and service.limitTo:
739 if not creds.hasCredentials(request.getUser(), request.getPassword(),
740 service.limitTo):
741 raise svcs.Authenticate()
742 else:
743 request.setHeader("x-vo-authenticated", request.getUser())
744
745 if self.checkedRenderer and self.name not in self.service.allowed:
746 raise svcs.ForbiddenURI(
747 "The renderer %s is not allowed on this service."%self.name,
748 rd=self.service.rd)
749
750 self.metaCarrier = self.service
751 self.macroPackage = self.service
752
753 # Set to true when we notice we need to fix the service's output fields
754 self.fieldsChanged = False
755
756 self._logRequestArgs(request)
757 self._fillServiceDefaults(request.strargs)
758
759 def _logRequestArgs(self, request):
760 """leaves the actual arguments of a request in the log.
761 """
762 try:
763 if request.strargs:
764 # even if there are args, don't log them if only boring ones
765 # were given
766 fmtArgs = _formatRequestArgs(request.strargs)
767 if fmtArgs!='{}':
768 log.msg("# Processing starts: %s %s"%(
769 request.path.decode("ascii", "ignore"),
770 fmtArgs))
771 except: # don't fail because of logging problems
772 base.ui.notifyError("Formatting of request strargs failed.")
773
774 def _fillServiceDefaults(self, args):
775 """a hook to enter default parameters based on the service.
776 """
777 if self.service.core.hasProperty("defaultSortKey"):
778 if "_DBOPTIONS_ORDER" not in args:
779 args["_DBOPTIONS_ORDER"] = self.service.core.getProperty(
780 "defaultSortKey").split(",")
781
782 def runSync(self, rawData):
783 """calls the actual service.
784
785 This will run in the current thread; you will usually
786 want to use runAsync from the main nevow event loop unless you know
787 the service is quick or actually works asynchronously.
788 """
789 return self.service.run(self, rawData, self.queryMeta)
790
791 def runAsync(self, rawData):
792 """takes raw data and returns a deferred firing the service result.
793
794 This will always return a deferred.
795 """
796 return threads.deferToThread(self.runSync, rawData)
797
798 def runAsyncWithFormalData(self, rawData, request):
799 """runs the service, taking arguments from material preparsed
800 by nevow formal.
801
802 This is the entry point for the form renderer and its friends.
803
804 Like runAsync, it always returns a deferred.
805 """
806 self.queryMeta["formal_data"] = rawData
807
808 # contextGrammar wants a dict of lists, whereas formal has direct
809 # values; accommodate to contextGrammar
810
811 if (self.service.core.outputTable.columns and
812 not self.service.getCurOutputFields(self.queryMeta)):
813 raise base.ValidationError("These output settings yield no"
814 " output fields", "_OUTPUT")
815
816 data = {}
817 for k, v in rawData.items():
818 if v is None or isinstance(v, list):
819 data[k] = v
820 else:
821 data[k] = [v]
822 return self.runAsync(svcs.PreparsedInput(data))
823
824 def data_serviceURL(self, renderer):
825 """returns a relative URL for this service using the renderer.
826
827 This is usually used like this:
828
829 <a><n:attr name="href" n:data="serviceURL info" n:render="data">x</a>
830 """
831 def get(request, data):
832 return self.service.getURL(renderer, absolute="False")
833 return get
834
835 def data_tableName(self, renderer, data):
836 """returns the name of the queried table on a core that has one,
837 and just "dachs_table" otherwise.
838
839 This is used, for instance, in making up SAMP result names.
840 """
841 qt = getattr(self.service.core, "queriedTable", None)
842 if qt:
843 return qt.id
844 else:
845 return "dachs_table"
846
847 @template.renderer
848 def servicerelative(self, request, tag):
849 """prepends the service's base URI to src and href attributes.
850
851 Use this to link to other renderings of the service.
852 """
853 def munge(key):
854 if key in tag.attributes:
855 tag.attributes[key] = self.service.getURL(
856 tag.attributes[key],
857 absolute=False)
858 munge("src")
859 munge("href")
860 return tag
861
862 def lookupRenderMethod(self, name):
863 """overrides parent lookupRenderMethod to also include custom
864 render functions from the service definition in the RD.
865 """
866 if name in self.service.nevowRenderers:
867 return types.MethodType(
868 self.service.nevowRenderers[name], self)
869 return nevowc.TemplatedPage.lookupRenderMethod(self, name)
870
871 def lookupDataMethod(self, name):
872 """overrides parent lookupDataMethod to also include data methods
873 coming from the service definition in the RD.
874 """
875 if name in self.service.nevowDataFunctions:
876 return types.MethodType(
877 self.service.nevowDataFunctions[name], self)
878 return nevowc.TemplatedPage.lookupDataMethod(self, name)
879
880 def getChild(self, name, request):
881 # By default, ServiceBasedPages have no directory-like resources.
882 # So, if some overzealous entity added a slash, just redirect.
883 # Do not upcall to this if you override getChild.
884 if name==b"":
885 raise svcs.WebRedirect(str(request.URLPath().parent()))
886 raise svcs.UnknownURI(f"{self.name} has no child resources")
887
888
889 if __name__=="__main__": # pragma: no cover
890 import doctest, grend
891 doctest.testmod(grend)