def productsRow(self): """returns the row in dc.products corresponding to this RAccref's accref, or raises a NotFoundError. """ try: return self._productsRowCache except AttributeError: pt = getProductsTable() res = list( pt.iterQuery(pt.tableDef, "accref=%(accref)s", {"accref": self.accref})) if not res: raise base.NotFoundError( self.accref, "accref", "product table", hint= "Product URLs may disappear, though in general they should" " not. If you have an IVOID (pubDID) for the file you are trying to" " locate, you may still find it by querying the ivoa.obscore table" " using TAP and ADQL.") self._productsRowCache = res[0] # make sure whatever can end up being written to something # file-like for key in ["mime", "accessPath", "accref"]: self._productsRowCache[key] = str(self._productsRowCache[key]) return self._productsRowCache
def getColumnById(self, id): """returns the column with id. It will raise a NotFoundError if no such column exists. """ try: return self.getIdIndex()[id] except KeyError: raise base.NotFoundError(id, what="column", within=self.withinId)
def getRenderer(name): if name not in RENDERER_REGISTRY: raise base.NotFoundError(name, "renderer", "registred renderers") cls = utils.loadInternalObject(*RENDERER_REGISTRY[name]) if cls.name != name: raise base.ReportableError( "Internal Error: Renderer %s is registred" " under the wrong name." % name, hint="This is probably a typo in svcs.renderers; it needs" " to be fixed there") return cls
def getNameForTemplate(template): """returns the name under which the FITS template has been registred. """ for name, namedTemplate in _TEMPLATE_NAMES: if template is namedTemplate: return name raise base.NotFoundError("template "+str(id(template)), "FITS template", "registred templates", hint="If you used a custom template," " have you called fitstricks.registerTemplate(name, template)" " for it?")
def getById(self, id, forceType=None): try: res = self.idmap[id] except KeyError: raise base.NotFoundError(id, "Element with id", "RD %s" % (self.sourceId)) if forceType: if not isinstance(res, forceType): raise base.StructureError("Element with id '%s' is not a %s" % (id, forceType.__name__)) return res
def getCore(name): if name not in CORE_REGISTRY: raise base.NotFoundError(name, "core", "registred cores") cls = utils.loadInternalObject(*CORE_REGISTRY[name]) if cls.name_ != name: raise base.ReportableError( "Internal Error: Core %s is registred" " under the wrong name." % name, hint="This is probably a typo in svcs.core; it needs" " to be fixed there") return cls
def getGrammar(grammarName): if grammarName not in GRAMMAR_REGISTRY: raise base.NotFoundError(grammarName, "grammar", "defined grammars") grammarClass = utils.loadInternalObject(*GRAMMAR_REGISTRY[grammarName]) if grammarClass.name_ != grammarName: raise base.ReportableError( "Internal Error: Grammar %s is registred" " under the wrong name." % grammarName, hint="This is probably a typo in grammars.__init__; it needs" " to be fixed there") return grammarClass
def getAuthFor(authKey): """returns a header dictionary to authenticate for authKey. authKey is a key into ~/.gavo/test.creds. """ try: user, pw = _loadCreds()[authKey] except KeyError: raise base.NotFoundError(authKey, "Authorization info", "~/.gavo/test.creds") return {'Authorization': "Basic "+( "%s:%s"%(user, pw)).encode("base64").strip()}
def getColumnByUtype(self, utype): """returns the column having utype. This should be unique, but this method does not check for uniqueness. """ utype = utype.lower() for item in self: if item.utype and item.utype.lower() == utype: return item raise base.NotFoundError(utype, what="column with utype", within=self.withinId)
def getTemplateForName(templateName): """returns the FITS template sequence for templateName. A NotFoundError is raised if no such template exists. """ for name, template in _TEMPLATE_NAMES: if name==templateName: return template raise base.NotFoundError(templateName, "FITS template", "registred templates", hint="If you used a custom template," " have you called fitstricks.registerTemplate(name, template)" " for it?")
def getByUtypes(self, *utypes): """returns the first param or column matching the first utype matching anything. """ for utype in utypes: try: return self.getByUtype(utype) except base.NotFoundError: pass raise base.NotFoundError(", ".join(utypes), what="param or column with utype in", within="table %s" % self.id)
def _resolveIdmaps(self, columns): """adds mappings for self's idmap within column set. """ existingMaps = set(m.key for m in self.maps) baseNames = [c.key for c in columns] for colName in self.idmaps: matching = fnmatch.filter(baseNames, colName) if not matching: raise base.NotFoundError(colName, "columns matching", "unknown") for dest in matching: if dest not in existingMaps: self.maps.append(MapRule(self, key=dest).finishElement(None)) self.idmaps = []
def getTableDef(tableName): """returns a tableDef instance for the schema-qualified tableName. If no such table is known to the system, a NotFoundError is raised. """ with base.AdhocQuerier(base.getTableConn) as q: res = list(q.query("SELECT tableName, sourceRD FROM dc.tablemeta WHERE" " LOWER(tableName)=LOWER(%(tableName)s)", {"tableName": tableName})) if len(res)!=1: raise base.NotFoundError(tableName, what="table", within="data center table listing.", hint="The table is missing from" " the dc.tablemeta table. This gets filled at gavoimp time.") tableName, rdId = res[0] return base.caches.getRD(rdId).getById(basename(tableName))
def getColumnByName(self, name): """returns the column with name. It will raise a NotFoundError if no such column exists. """ try: return self[self.nameIndex[name]] except KeyError: try: return self[self.nameIndex[utils.QuotedName(name)]] except KeyError: raise base.NotFoundError(name, what="column", within=self.withinId)
def getNote(self, noteTag): """returns the table note meta value for noteTag. This will raise a NotFoundError if we don't have such a note. You will not usually use this to retrieve meta items since columns have the meta values in their note attributes. Columns, of course, use this to get their note attribute value. """ mi = self.getMeta("note") or [] for mv in mi: if mv.tag == noteTag: return mv else: raise base.NotFoundError(noteTag, what="note tag", within="table %s" % self.id)
def getResobFromRestup(restup): """returns a resob for a res tuple. restup at least has to contain the sourceRD and resId fields. The item that is being returned is either a service or a NonServiceResource (including DeletedResource). All of these have a getMeta method and should be able to return the standard DC metadata. """ if restup["deleted"]: return base.makeStruct(nonservice.DeletedResource, resTuple=restup) sourceRD, resId = restup["sourceRD"], restup["resId"] try: return base.caches.getRD(sourceRD).getById(resId) except KeyError: raise base.ui.logOldExc( base.NotFoundError(resId, what="service", within="RD %s" % sourceRD, hint="This usually happens when you" " forgot to run gavopublish %s" % sourceRD))
class _UserConfigFakeRD(object): """A fake object that's in the RD cache as "%". This is used by the id resolvers in parsecontext; this certainly is of no use as an RD otherwise. """ def __init__(self): pass def getRealRD(self): return base.caches.getRD(USERCONFIG_RD_PATH) def getMeta(self, *args, **kwargs): return base.caches.getRD(USERCONFIG_RD_PATH).getMeta(*args, **kwargs) def getById(self, id, forceType=None): """returns an item from userconfig. This first tries to resolve id in gavo/etc/userconfig.rd, then in the fallback //userconfig.rd. """ try: try: return base.caches.getRD( os.path.join(base.getConfig("configDir"), "userconfig.rd")).getById(id, forceType=forceType) except base.NotFoundError: pass except Exception, msg: base.ui.notifyError("Bad userconfig: (%s), ignoring it. Run" " 'gavo val %%' to see actual errors." % repr(msg)) return base.caches.getRD("//userconfig").getById( id, forceType=forceType) except base.NotFoundError: raise base.NotFoundError(id, "Element with id", "etc/userconfig.rd")
def getTableDefForTable(self, tableName): """returns a TableDef for tableName. As it is not a priori clear which RD a given table lives in, this goes through dc.tablemeta to figure this out. The object comes from the actual RD, though, so this might very well trigger database action and RD loading. """ if not "." in tableName: tableName = "public."+tableName for row in self.readerConnection.queryToDicts( "select sourcerd, tablename from dc.tablemeta where" " lower(tableName)=%(tableName)s", {"tableName": tableName.lower()}): break else: raise base.ui.logOldExc( base.NotFoundError(tableName, "table", "dc_tables")) return base.caches.getRD(row["sourcerd"] ).getById(row["tablename"].split(".")[-1])
def resolveName(instance, context, id): if hasattr(instance, "parentTable"): try: return base.resolveNameBased(instance.parentTable, id) except base.NotFoundError: # try on real name path pass if hasattr(instance, "getByName"): try: return instance.getByName(id) except base.NotFoundError: pass np = instance.namePath if np is None and instance.parent: np = getattr(instance.parent, "namePath", None) if np is None: raise base.NotFoundError(id, "Element with name", repr(self), hint="No namePath here") res = context.resolveId(np + "." + id) return res
def getNSForPrefix(self, prefix): try: return self._registry[prefix] except KeyError: raise base.NotFoundError(prefix, "XML namespace prefix", "registry of prefixes.")