| 1 |
""" |
| 2 |
Description and handling of inputs to services. |
| 3 |
|
| 4 |
This module in particular describes the InputKey, the primary means |
| 5 |
of describing input widgets and their processing. |
| 6 |
|
| 7 |
They are collected in contextGrammars, entities creating inputArgs |
| 8 |
items. |
| 9 |
""" |
| 10 |
|
| 11 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 12 |
#c |
| 13 |
#c This program is free software, covered by the GNU GPL. See the |
| 14 |
#c COPYING file in the source distribution. |
| 15 |
|
| 16 |
|
| 17 |
from gavo import base |
| 18 |
from gavo import grammars |
| 19 |
from gavo import rscdef |
| 20 |
from gavo import votable |
| 21 |
from gavo import utils |
| 22 |
from gavo.rscdef import column |
| 23 |
from gavo.rscdef import rmkfuncs |
| 24 |
from gavo.svcs import dalipars |
| 25 |
from gavo.svcs import pql |
| 26 |
from gavo.svcs import vizierexprs |
| 27 |
|
| 28 |
MS = base.makeStruct |
| 29 |
|
| 30 |
|
| 31 |
_RENDERER_ADAPTORS = { |
| 32 |
'form': vizierexprs.adaptInputKey, |
| 33 |
'pql': pql.adaptInputKey, |
| 34 |
'dali': dalipars.adaptInputKey, |
| 35 |
} |
| 36 |
|
| 37 |
def getRendererAdaptor(renderer): |
| 38 |
"""returns a function that returns input keys adapted for renderer. |
| 39 |
|
| 40 |
The function returns None if no adapter is necessary. This |
| 41 |
only takes place for inputKeys within a buildFrom condDesc. |
| 42 |
""" |
| 43 |
return _RENDERER_ADAPTORS.get(renderer.parameterStyle) |
| 44 |
|
| 45 |
|
| 46 |
@base.buildstructure |
| 47 |
class InputKey(column.ParamBase): |
| 48 |
"""A description of a piece of input. |
| 49 |
|
| 50 |
Think of inputKeys as abstractions for input fields in forms, though |
| 51 |
they are used for services not actually exposing HTML forms as well. |
| 52 |
|
| 53 |
Some of the DDL-type attributes (e.g., references) only make sense here |
| 54 |
if columns are being defined from the InputKey. |
| 55 |
|
| 56 |
Properties evaluated: |
| 57 |
|
| 58 |
* defaultForForm -- a value entered into form fields by default |
| 59 |
(be stingy with those; while it's nice to not have to set things |
| 60 |
presumably right for almost everyone, having to delete stuff |
| 61 |
you don't want over and over is really annoying). |
| 62 |
* adaptToRenderer -- a true boolean literal here causes the param |
| 63 |
to be adapted for the renderer (e.g., float could become vexpr-float). |
| 64 |
You'll usually not want this, because the expressions are |
| 65 |
generally evaluated by the database, and the condDescs do the |
| 66 |
adaptation themselves. This is mainly for rare situations like |
| 67 |
file uploads in custom cores. |
| 68 |
* notForRenderer -- a renderer name for which this inputKey is suppressed |
| 69 |
* onlyForRenderer -- a renderer name for which this inputKey will be |
| 70 |
preserved; it will be dropped for all others. |
| 71 |
""" |
| 72 |
name_ = "inputKey" |
| 73 |
|
| 74 |
# XXX TODO: make widgetFactory and showItems properties. |
| 75 |
_widgetFactory = base.UnicodeAttribute("widgetFactory", default=None, |
| 76 |
description="A python expression for a custom widget" |
| 77 |
" factory for this input," |
| 78 |
" e.g., 'Hidden' or 'widgetFactory(TextArea, rows=15, cols=30)'", |
| 79 |
copyable=True) |
| 80 |
_showItems = base.IntAttribute("showItems", default=3, |
| 81 |
description="Number of items to show at one time on selection widgets.", |
| 82 |
copyable=True) |
| 83 |
_inputUnit = base.UnicodeAttribute("inputUnit", default=None, |
| 84 |
description="Override unit of the table column with this.", |
| 85 |
copyable=True) |
| 86 |
_std = base.BooleanAttribute("std", default=False, |
| 87 |
description="Is this input key part of a standard interface for" |
| 88 |
" registry purposes?", |
| 89 |
copyable=True) |
| 90 |
_multiplicity = base.UnicodeAttribute("multiplicity", default=None, |
| 91 |
copyable=True, |
| 92 |
description="Set" |
| 93 |
" this to single to have an atomic value (chosen at random" |
| 94 |
" if multiple input values are given)," |
| 95 |
" forced-single to have an atomic value" |
| 96 |
" and raise an exception if multiple values come in, or" |
| 97 |
" multiple to receive lists. On the form renderer, this is" |
| 98 |
" ignored, and the values are what gavo.formal passes in." |
| 99 |
" If not given, it is single unless there is a values element with" |
| 100 |
" options, in which case it's multiple.") |
| 101 |
_preparse = base.UnicodeAttribute("preparse", default=base.NotGiven, |
| 102 |
description="Function body morphing the input string before the" |
| 103 |
" type parser sees it. This must return a string or raise an" |
| 104 |
" Exception (that will be turned into a ValidationError). The" |
| 105 |
" input string is available as input. Note that need to be able" |
| 106 |
" to handle incoming None-s gracefully (e.g.," |
| 107 |
" ``input and input.lower()``).", |
| 108 |
copyable=True) |
| 109 |
|
| 110 |
# Don't validate meta for these -- while they are children |
| 111 |
# of validated structures (services), they don't need any |
| 112 |
# meta at all. This should go as soon as we have a sane |
| 113 |
# inheritance hierarchy for tables. |
| 114 |
metaModel = None |
| 115 |
|
| 116 |
_compiledPreparse = None |
| 117 |
|
| 118 |
def completeElement(self, ctx): |
| 119 |
super().completeElement(ctx) |
| 120 |
if self.restrictedMode and ( |
| 121 |
self.widgetFactory |
| 122 |
or self.preparse): |
| 123 |
raise base.RestrictedElement(self.name_, |
| 124 |
hint="The preparse and widgetFactory attribute are not allowed" |
| 125 |
" in restricted mode.") |
| 126 |
|
| 127 |
if self.preparse: |
| 128 |
code = ("def preparse(input):\n" |
| 129 |
+utils.fixIndentation(self.preparse, " ")+"\n") |
| 130 |
compiledPreparse = rmkfuncs.makeProc( |
| 131 |
"preparse", code, "", None, |
| 132 |
self.getSourcePosition()) |
| 133 |
oldParse = self._parse |
| 134 |
self._parse = (lambda literal, atom=False: |
| 135 |
oldParse(compiledPreparse(literal), atom)) |
| 136 |
|
| 137 |
if self.multiplicity is None: |
| 138 |
if self.isEnumerated(): |
| 139 |
self.multiplicity = "multiple" |
| 140 |
else: |
| 141 |
self.multiplicity = "single" |
| 142 |
|
| 143 |
def onElementComplete(self): |
| 144 |
super().onElementComplete() |
| 145 |
# compute scaling if an input unit is given |
| 146 |
self.scaling = None |
| 147 |
if self.inputUnit: |
| 148 |
self.scaling = base.computeConversionFactor(self.inputUnit, self.unit) |
| 149 |
|
| 150 |
def onParentComplete(self): |
| 151 |
if self.parent and hasattr(self.parent, "required"): |
| 152 |
# children of condDescs inherit their requiredness |
| 153 |
# (unless defaulted) |
| 154 |
self.required = self.parent.required |
| 155 |
# but if there's a default, never require an input |
| 156 |
if self.value: |
| 157 |
self.required = False |
| 158 |
|
| 159 |
def validateValue(self, literal): |
| 160 |
"""raises a ValidationError if literal cannot be deserialised into |
| 161 |
an acceptable value for self. |
| 162 |
""" |
| 163 |
self._parse(literal) |
| 164 |
|
| 165 |
def computeCoreArgValue(self, inputList, ensureRequired=True): |
| 166 |
"""parses some input for this input key. |
| 167 |
|
| 168 |
This takes into account multiplicities, type conversions, and |
| 169 |
all the remaining horrors. |
| 170 |
|
| 171 |
It will return a list or a single value, depending on multiplity. |
| 172 |
""" |
| 173 |
# we really ought to get rid of automatic listification, but |
| 174 |
# I'm sure we'll break someone's stuff if we do. Ah well. |
| 175 |
if not isinstance(inputList, list): |
| 176 |
if inputList is None: |
| 177 |
inputList = [] |
| 178 |
else: |
| 179 |
if self.type!="raw": |
| 180 |
base.ui.notifyWarning( |
| 181 |
f"Non-list input to ContextGrammar: {self.name}") |
| 182 |
inputList = [inputList] |
| 183 |
|
| 184 |
# twisted started having [''] for empty parameters at some point. |
| 185 |
# Let's hope we never need empty strings in parameters. |
| 186 |
if self.type!="raw": |
| 187 |
inputList = [i for i in inputList if i] |
| 188 |
|
| 189 |
if not inputList: |
| 190 |
if self.value is not None: |
| 191 |
inputList = [self.value] |
| 192 |
|
| 193 |
elif self.values and self.values.default: |
| 194 |
inputList = [self.values.default] |
| 195 |
|
| 196 |
elif ensureRequired and self.required: |
| 197 |
raise base.ValidationError( |
| 198 |
"Required parameter '%s' missing."%self.name, |
| 199 |
self.name) |
| 200 |
|
| 201 |
else: |
| 202 |
return None |
| 203 |
|
| 204 |
if self.type=="raw": |
| 205 |
return inputList |
| 206 |
|
| 207 |
if self.multiplicity=="forced-single" and len(inputList)>1: |
| 208 |
raise base.MultiplicityError( |
| 209 |
"Inputs for the parameter %s must not have more than" |
| 210 |
" one value; however, %s was passed in."%( |
| 211 |
self.name, |
| 212 |
str(inputList)), |
| 213 |
colName=self.name) |
| 214 |
|
| 215 |
if self.multiplicity=="multiple": |
| 216 |
vals = [v for v in (self._parse(val) for val in inputList) |
| 217 |
if v is not None] |
| 218 |
return vals or None |
| 219 |
|
| 220 |
else: |
| 221 |
if inputList: |
| 222 |
return self._parse(inputList[-1]) |
| 223 |
else: |
| 224 |
return None |
| 225 |
|
| 226 |
@classmethod |
| 227 |
def fromColumn(cls, column, **kwargs): |
| 228 |
"""returns an InputKey for query input to column. |
| 229 |
""" |
| 230 |
if isinstance(column, InputKey): |
| 231 |
if kwargs: |
| 232 |
return column.change(**kwargs) |
| 233 |
else: |
| 234 |
return column |
| 235 |
|
| 236 |
instance = cls(None) |
| 237 |
instance.feedObject("original", column) |
| 238 |
|
| 239 |
for k,v in kwargs.items(): |
| 240 |
instance.feed(k, v) |
| 241 |
if not "required" in kwargs: |
| 242 |
instance.feedObject("required", False) |
| 243 |
instance.dmRoles = rscdef.OldRoles(column.dmRoles) |
| 244 |
return instance.finishElement(None) |
| 245 |
|
| 246 |
|
| 247 |
def filterInputKeys(keys, rendName, adaptor=None): |
| 248 |
"""filters inputKeys in key, only returning those compatible with |
| 249 |
rendName. |
| 250 |
|
| 251 |
adaptor is is a function taking and returning an inputKey that is used |
| 252 |
for input keys with an adaptToRenderer property. |
| 253 |
""" |
| 254 |
for key in keys: |
| 255 |
if key.getProperty("onlyForRenderer", None) is not None: |
| 256 |
if key.getProperty("onlyForRenderer")!=rendName: |
| 257 |
continue |
| 258 |
if key.getProperty("notForRenderer", None) is not None: |
| 259 |
if key.getProperty("notForRenderer")==rendName: |
| 260 |
continue |
| 261 |
|
| 262 |
if base.parseBooleanLiteral(key.getProperty("adaptToRenderer", "False") |
| 263 |
) and adaptor: |
| 264 |
key = adaptor(key) |
| 265 |
|
| 266 |
yield key |
| 267 |
|
| 268 |
|
| 269 |
@base.buildstructure |
| 270 |
class InputTD(base.Structure, base.StandardMacroMixin): |
| 271 |
"""an input for a core. |
| 272 |
|
| 273 |
These aren't actually proper tables but actually just collection of |
| 274 |
the param-like inputKeys. They serve as input declarations for cores |
| 275 |
and services (where services derive their inputTDs from the cores' ones by |
| 276 |
adapting them to the current renderer. Their main use is for the derivation |
| 277 |
of contextGrammars. |
| 278 |
|
| 279 |
They can carry metadata, though, which is sometimes convenient when |
| 280 |
transporting information from the parameter parsers to the core. |
| 281 |
|
| 282 |
For the typical dbCores (and friends), these are essentially never |
| 283 |
explicitly defined but rather derived from condDescs. |
| 284 |
|
| 285 |
Do *not* read input values by using table.getParam. This will only |
| 286 |
give you one value when a parameter has been given multiple times. |
| 287 |
Instead, use the output of the contextGrammar (inputParams in condDescs). |
| 288 |
Only there you will have the correct multiplicities. |
| 289 |
""" |
| 290 |
name_ = "inputTable" |
| 291 |
|
| 292 |
_inputKeys = rscdef.ColumnListAttribute("inputKeys", |
| 293 |
childFactory=InputKey, |
| 294 |
description='Input parameters for this table.', |
| 295 |
copyable=True) |
| 296 |
|
| 297 |
_groups = base.StructListAttribute("groups", |
| 298 |
childFactory=rscdef.Group, |
| 299 |
description="Groups of inputKeys (this is used for form UI formatting).", |
| 300 |
copyable=True) |
| 301 |
|
| 302 |
_exclusive = base.BooleanAttribute("exclusive", |
| 303 |
description="If true, context grammars built from this will" |
| 304 |
" raise an error if contexts passed in have keys not defined" |
| 305 |
" by this table", |
| 306 |
default=False, |
| 307 |
copyable=True) |
| 308 |
_rd = rscdef.RDAttribute() |
| 309 |
|
| 310 |
def __iter__(self): |
| 311 |
return iter(self.inputKeys) |
| 312 |
|
| 313 |
def adaptForRenderer(self, renderer): |
| 314 |
"""returns an inputTD tailored for renderer. |
| 315 |
|
| 316 |
This is discussed in svcs.core's module docstring. |
| 317 |
""" |
| 318 |
newKeys = list( |
| 319 |
filterInputKeys(self.inputKeys, renderer.name, |
| 320 |
getRendererAdaptor(renderer))) |
| 321 |
|
| 322 |
if newKeys!=self.inputKeys: |
| 323 |
return self.change(inputKeys=newKeys, parent_=self) |
| 324 |
else: |
| 325 |
return self |
| 326 |
|
| 327 |
def resolveName(self, ctx, name): |
| 328 |
"""returns a column name from a queried table of the embedding core, |
| 329 |
if available. |
| 330 |
|
| 331 |
This is a convenicence hack that lets people reference columns from |
| 332 |
a TableBasedCore by their simple, non-qualified names. |
| 333 |
""" |
| 334 |
if self.parent and hasattr(self.parent, "queriedTable"): |
| 335 |
return self.parent.queriedTable.resolveName(ctx, name) |
| 336 |
raise base.NotFoundError(id, "Element with id or name", "name path", |
| 337 |
hint="There is no queried table this name could be resolved in.") |
| 338 |
|
| 339 |
|
| 340 |
class CoreArgs(base.MetaMixin): |
| 341 |
"""A container for core arguments. |
| 342 |
|
| 343 |
There's inputTD, which reference the renderer-adapted input table, |
| 344 |
and args, the ContextGrammar processed input. For kicks, we also |
| 345 |
have rawArgs, which is the contextGrammar's input (if you find |
| 346 |
you're using it, tell us; that's pointing to a problem on our side). |
| 347 |
|
| 348 |
getParam(name) -> value and getParamDict() -> dict methods are |
| 349 |
present for backward compatibility. |
| 350 |
""" |
| 351 |
def __init__(self, inputTD, args, rawArgs): |
| 352 |
self.inputTD, self.args, self.rawArgs = inputTD, args, rawArgs |
| 353 |
base.MetaMixin.__init__(self) |
| 354 |
|
| 355 |
def getParam(self, name): |
| 356 |
return self.args.get(name) |
| 357 |
|
| 358 |
def getParamDict(self): |
| 359 |
return self.args |
| 360 |
|
| 361 |
def update(self, other): |
| 362 |
"""adds (and overwrites) the parameters from another CoreArgs instance |
| 363 |
to this. |
| 364 |
|
| 365 |
This is used in UWS processing, where generic and service-specific |
| 366 |
parameters are parsed in two steps. |
| 367 |
|
| 368 |
Right now, the inputTD is taken from other; we *may* find that we |
| 369 |
need to merge the two inputTDs later, so there are no guarantees |
| 370 |
that the first inputKeys disappear. |
| 371 |
|
| 372 |
We also assume that the rawArgs are always the same. |
| 373 |
""" |
| 374 |
self.args.update(other.args) |
| 375 |
self.inputTD = other.inputTD |
| 376 |
|
| 377 |
@classmethod |
| 378 |
def fromRawArgs(cls, inputTD, rawArgs, contextGrammar=None): |
| 379 |
"""returns a CoreArgs instance built from an inputDD and |
| 380 |
ContextGrammar-parseable rawArgs. |
| 381 |
|
| 382 |
contextGrammar can be overridden, e.g., to cache or to add |
| 383 |
extra, non-core keys. |
| 384 |
""" |
| 385 |
if contextGrammar is None: |
| 386 |
contextGrammar = MS(ContextGrammar, inputTD=inputTD) |
| 387 |
ri = contextGrammar.parse(rawArgs) |
| 388 |
_ = list(ri) #noflake: ignored value |
| 389 |
return cls(inputTD, ri.getParameters(), rawArgs) |
| 390 |
|
| 391 |
|
| 392 |
class ContextRowIterator(grammars.RowIterator): |
| 393 |
"""is a row iterator over "contexts", i.e. single dictionary-like objects. |
| 394 |
|
| 395 |
The source token expected here can be a request.strargs style dictionary |
| 396 |
with lists of strings as arguments, or a parsed dictionary from |
| 397 |
gavo.formal. Non-list literals in the latter are packed into a list to ensure |
| 398 |
consistent behaviour. |
| 399 |
""" |
| 400 |
def __init__(self, grammar, sourceToken, **kwargs): |
| 401 |
self.locator = "(internal)" |
| 402 |
self.ensureRequired = True # hack for the benefit of parseStrargs |
| 403 |
grammars.RowIterator.__init__(self, grammar, |
| 404 |
utils.CaseSemisensitiveDict(sourceToken), |
| 405 |
**kwargs) |
| 406 |
|
| 407 |
def _ensureNoExtras(self): |
| 408 |
"""makes sure sourceToken has no keys not mentioned in the grammar. |
| 409 |
|
| 410 |
Here, we assume case-insensitive arguments for now. If we ever |
| 411 |
want to change that... oh, my. |
| 412 |
|
| 413 |
This is only executed for grammars with rejectExtras. |
| 414 |
""" |
| 415 |
inKeys = set(n.lower() for n in self.sourceToken) |
| 416 |
expectedKeys = set(k.name.lower() for k in self.grammar.iterInputKeys()) |
| 417 |
|
| 418 |
if inKeys-expectedKeys: |
| 419 |
badKeys = inKeys-expectedKeys |
| 420 |
|
| 421 |
if len(badKeys)==1: |
| 422 |
fieldName = next(iter(badKeys)) |
| 423 |
else: |
| 424 |
fieldName = "(various)" |
| 425 |
|
| 426 |
raise base.ValidationError("The following parameter(s) are" |
| 427 |
" not accepted by this service: %s"%",".join( |
| 428 |
sorted(badKeys)), |
| 429 |
fieldName) |
| 430 |
|
| 431 |
def _iterRows(self): |
| 432 |
# we don't really return any rows, but this is where our result |
| 433 |
# dictionary is built. |
| 434 |
if self.grammar.rejectExtras: |
| 435 |
self._ensureNoExtras() |
| 436 |
|
| 437 |
self.coreArgs = {} |
| 438 |
|
| 439 |
for ik in self.grammar.iterInputKeys(): |
| 440 |
self.locator = "param %s"%ik.name |
| 441 |
try: |
| 442 |
self.coreArgs[ik.name] = ik.computeCoreArgValue( |
| 443 |
self.sourceToken.get(ik.name), |
| 444 |
ensureRequired=self.ensureRequired) |
| 445 |
except (ValueError, votable.BadVOTableLiteral) as ex: |
| 446 |
raise base.ValidationError("Bad parameter literal %s (%s)"%( |
| 447 |
self.sourceToken.get(ik.name), ex), |
| 448 |
ik.name) |
| 449 |
|
| 450 |
if False: |
| 451 |
yield {} # contextGrammars yield no rows. |
| 452 |
|
| 453 |
def getParameters(self): |
| 454 |
return self.coreArgs |
| 455 |
|
| 456 |
def getLocator(self): |
| 457 |
return self.locator |
| 458 |
|
| 459 |
|
| 460 |
@base.buildstructure |
| 461 |
class ContextGrammar(grammars.Grammar): |
| 462 |
"""A grammar for web inputs. |
| 463 |
|
| 464 |
The source tokens for context grammars are dictionaries; these |
| 465 |
are either typed dictionaries from gavo.formal, where the values |
| 466 |
usually are atomic, or, preferably, the dictionaries of lists |
| 467 |
from request.strargs. |
| 468 |
|
| 469 |
ContextGrammars never yield rows, so they're probably fairly useless |
| 470 |
in normal circumstances. |
| 471 |
|
| 472 |
In normal usage, they just yield a single parameter row, |
| 473 |
corresponding to the source dictionary possibly completed with |
| 474 |
defaults, where non-requried input keys get None defaults where not |
| 475 |
given. Missing required parameters yield errors. |
| 476 |
|
| 477 |
This parameter row honors the multiplicity specification, i.e., single or |
| 478 |
forced-single are just values, multiple are lists. The content are |
| 479 |
*parsed* values (using the InputKeys' parsers). |
| 480 |
|
| 481 |
Since most VO protocols require case-insensitive matching of parameter |
| 482 |
names, matching of input key names and the keys of the input dictionary |
| 483 |
is attempted first literally, then disregarding case. |
| 484 |
|
| 485 |
Since ContextGrammars can be parents of inputKeys and thus are a |
| 486 |
bit table-like, they can also carry metadata. |
| 487 |
""" |
| 488 |
name_ = "contextGrammar" |
| 489 |
|
| 490 |
_inputTD = base.ReferenceAttribute("inputTD", |
| 491 |
default=base.NotGiven, |
| 492 |
description="The input table from which to take the input keys", |
| 493 |
copyable=True) |
| 494 |
|
| 495 |
_inputKeys = base.StructListAttribute("inputKeys", |
| 496 |
childFactory=InputKey, |
| 497 |
description="Extra input keys not defined in the inputTD. This" |
| 498 |
" is used when services want extra input processed by them rather" |
| 499 |
" than their core.", |
| 500 |
copyable=True) |
| 501 |
|
| 502 |
_original = base.OriginalAttribute("original") |
| 503 |
|
| 504 |
rowIterator = ContextRowIterator |
| 505 |
|
| 506 |
rejectExtras = False |
| 507 |
|
| 508 |
def onElementComplete(self): |
| 509 |
super().onElementComplete() |
| 510 |
if self.inputTD: |
| 511 |
self.rejectExtras = self.inputTD.exclusive |
| 512 |
else: |
| 513 |
self.rejectExtras = False |
| 514 |
|
| 515 |
def iterInputKeys(self): |
| 516 |
if self.inputTD: |
| 517 |
for ik in self.inputTD: |
| 518 |
yield ik |
| 519 |
for ik in self.inputKeys: |
| 520 |
yield ik |
| 521 |
|
| 522 |
def parseStrargs(self, strargs, ensureRequired=True): |
| 523 |
"""returns parsed parameters from a request.strargs dict. |
| 524 |
|
| 525 |
This is a convenience method appropriate here because, really, |
| 526 |
ContextGrammars never yield rows, and hence the calling convention |
| 527 |
is a bit counter-intuitive. |
| 528 |
|
| 529 |
ensureRequired=False asks the context grammar to not complain |
| 530 |
if required values are missing. That is important in UWS operation, |
| 531 |
where parameters may be set incrementally. |
| 532 |
""" |
| 533 |
ri = self.parse(strargs) |
| 534 |
ri.ensureRequired = ensureRequired |
| 535 |
list(ri) |
| 536 |
return ri.getParameters() |