| 1 |
""" |
| 2 |
"Output drivers" for various formats, for the use of form-like renderers. |
| 3 |
|
| 4 |
TODO: Tar and the output format widget should go somewhere else; the |
| 5 |
rest should be done by RESPONSEFORMAT and formats. Then this module |
| 6 |
should die. |
| 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 os |
| 16 |
|
| 17 |
from twisted.internet import threads |
| 18 |
from twisted.web.template import tags as T |
| 19 |
|
| 20 |
from gavo import base |
| 21 |
from gavo import formats |
| 22 |
from gavo import utils |
| 23 |
from gavo.formats import csvtable #noflake: format registration |
| 24 |
from gavo.formats import jsontable #noflake: format registration |
| 25 |
from gavo.formats import fitstable #noflake: format registration |
| 26 |
from gavo.formats import texttable #noflake: format registration |
| 27 |
from gavo.formats import geojson #noflake: format registration |
| 28 |
from gavo.formal import types as formaltypes |
| 29 |
from gavo.formal.util import render_cssid |
| 30 |
from gavo.protocols import products |
| 31 |
from gavo.svcs import customwidgets |
| 32 |
from gavo.svcs import streaming |
| 33 |
from gavo.web import producttar |
| 34 |
|
| 35 |
__docformat__ = "restructuredtext en" |
| 36 |
|
| 37 |
|
| 38 |
class ServiceResult(object): |
| 39 |
"""A base class for objects producing formatted output. |
| 40 |
|
| 41 |
They are basically wrappers for _formatOutput, which |
| 42 |
will usually be used as sources for streaming.streamOut. |
| 43 |
|
| 44 |
All methods on these objects are class methods -- they are never |
| 45 |
instantiated. |
| 46 |
|
| 47 |
Deriving classes can override |
| 48 |
|
| 49 |
- _formatOutput(result, request, queryMeta) -- receives the service result |
| 50 |
and arranges for it to be written. |
| 51 |
- canWrite(colSeq) -- a that returns true when a seq of columns |
| 52 |
can be serialized by this service result. |
| 53 |
- code -- an identifier used in HTTP query strings to select the format |
| 54 |
- label (optional) -- a string that is used in HTML forms to select |
| 55 |
the format (defaults to label). |
| 56 |
- compute -- if False, at least the form renderer will not run |
| 57 |
the service (this is when you just return a container). |
| 58 |
""" |
| 59 |
|
| 60 |
compute = True |
| 61 |
code = None |
| 62 |
label = None |
| 63 |
|
| 64 |
@classmethod |
| 65 |
def _formatOutput(cls, res, request, queryMeta): |
| 66 |
return b"" |
| 67 |
|
| 68 |
@classmethod |
| 69 |
def getLabel(cls): |
| 70 |
if cls.label is not None: |
| 71 |
return cls.label |
| 72 |
return cls.code |
| 73 |
|
| 74 |
@classmethod |
| 75 |
def canWrite(cls, colSeq): |
| 76 |
return True |
| 77 |
|
| 78 |
|
| 79 |
class VOTableResult(ServiceResult): |
| 80 |
"""A ResultFormatter for VOTables. |
| 81 |
|
| 82 |
The VOTables come as attachments, i.e., if all goes well the form |
| 83 |
will just stand as it is. |
| 84 |
""" |
| 85 |
code = "VOTable" |
| 86 |
|
| 87 |
@classmethod |
| 88 |
def _formatOutput(cls, data, request, queryMeta): |
| 89 |
if base.getMetaText(data.getPrimaryTable(), "_queryStatus" |
| 90 |
)=="OVERFLOW": |
| 91 |
fName = "truncated_votable.xml" |
| 92 |
else: |
| 93 |
fName = "votable.xml" |
| 94 |
request.setHeader("content-type", base.votableType) |
| 95 |
request.setHeader('content-disposition', |
| 96 |
'attachment; filename=%s'%fName) |
| 97 |
return streaming.streamVOTable(request, data, queryMeta) |
| 98 |
|
| 99 |
|
| 100 |
class FITSTableResult(ServiceResult): |
| 101 |
"""returns data as a FITS binary table. |
| 102 |
""" |
| 103 |
code = "FITS" |
| 104 |
label = "FITS table" |
| 105 |
|
| 106 |
@classmethod |
| 107 |
def getTargetName(cls, data): |
| 108 |
if base.getMetaText(data.getPrimaryTable(), "_queryStatus" |
| 109 |
)=="OVERFLOW": |
| 110 |
return "truncated_data.fits", "application/x-fits" |
| 111 |
else: |
| 112 |
return "data.fits", "application/x-fits" |
| 113 |
|
| 114 |
@classmethod |
| 115 |
def _formatOutput(cls, data, request, queryMeta): |
| 116 |
return threads.deferToThread(fitstable.makeFITSTableFile, data |
| 117 |
).addCallback(cls._serveFile, data, request) |
| 118 |
|
| 119 |
@classmethod |
| 120 |
def _serveFile(cls, filePath, data, request): |
| 121 |
name, mime = cls.getTargetName(data) |
| 122 |
request.setHeader("content-type", mime) |
| 123 |
request.setHeader('content-disposition', |
| 124 |
'attachment; filename=%s'%name) |
| 125 |
|
| 126 |
def writeData(dest): |
| 127 |
try: |
| 128 |
with open(filePath, "rb") as f: |
| 129 |
utils.cat(f, dest) |
| 130 |
finally: |
| 131 |
os.unlink(filePath) |
| 132 |
|
| 133 |
return streaming.streamOut(writeData, request) |
| 134 |
|
| 135 |
|
| 136 |
class TSVResponse(ServiceResult): |
| 137 |
code = "TSV" |
| 138 |
label = "Text (with Tabs)" |
| 139 |
|
| 140 |
@classmethod |
| 141 |
def _formatOutput(cls, data, request, queryMeta): |
| 142 |
request.setHeader("content-type", "text/tab-separated-values") |
| 143 |
|
| 144 |
def produceData(destFile): |
| 145 |
content = texttable.getAsText(data) |
| 146 |
destFile.write(content) |
| 147 |
|
| 148 |
return streaming.streamOut(produceData, request, queryMeta) |
| 149 |
|
| 150 |
|
| 151 |
class TextResponse(ServiceResult): |
| 152 |
code = "txt" |
| 153 |
label = "Text (fixed columns)" |
| 154 |
|
| 155 |
@classmethod |
| 156 |
def _formatOutput(cls, data, request, queryMeta): |
| 157 |
request.setHeader("content-type", "text/plain") |
| 158 |
|
| 159 |
def produceData(destFile): |
| 160 |
formats.formatData("txt", data, |
| 161 |
request, acquireSamples=False) |
| 162 |
|
| 163 |
return streaming.streamOut(produceData, request, queryMeta) |
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
class CSVResponse(ServiceResult): |
| 168 |
code = "CSV" |
| 169 |
label = "CSV" |
| 170 |
|
| 171 |
@classmethod |
| 172 |
def _formatOutput(cls, data, request, queryMeta): |
| 173 |
request.setHeader('content-disposition', |
| 174 |
'attachment; filename=table.csv') |
| 175 |
request.setHeader("content-type", "text/csv;header=present") |
| 176 |
|
| 177 |
def produceData(destFile): |
| 178 |
formats.formatData("csv", data, |
| 179 |
request, acquireSamples=False) |
| 180 |
|
| 181 |
return streaming.streamOut(produceData, request, queryMeta) |
| 182 |
|
| 183 |
|
| 184 |
class JsonResponse(ServiceResult): |
| 185 |
code = "JSON" |
| 186 |
label = "JSON" |
| 187 |
|
| 188 |
@classmethod |
| 189 |
def _formatOutput(cls, data, request, queryMeta): |
| 190 |
request.setHeader('content-disposition', |
| 191 |
'attachment; filename=table.json') |
| 192 |
request.setHeader("content-type", "application/json") |
| 193 |
|
| 194 |
def produceData(destFile): |
| 195 |
formats.formatData("json", data, |
| 196 |
request, acquireSamples=False) |
| 197 |
|
| 198 |
return streaming.streamOut(produceData, request, queryMeta) |
| 199 |
|
| 200 |
|
| 201 |
class TarResponse(ServiceResult): |
| 202 |
"""delivers a tar of products requested. |
| 203 |
""" |
| 204 |
code = "tar" |
| 205 |
|
| 206 |
@classmethod |
| 207 |
def _formatOutput(cls, data, request, queryMeta): |
| 208 |
return producttar.getTarMaker().deliverProductTar( |
| 209 |
data, request, queryMeta) |
| 210 |
|
| 211 |
@classmethod |
| 212 |
def canWrite(cls, colSeq): |
| 213 |
if products.getProductColumns(colSeq): |
| 214 |
return True |
| 215 |
return False |
| 216 |
|
| 217 |
|
| 218 |
################# Helpers |
| 219 |
|
| 220 |
|
| 221 |
_getFormat = utils.buildClassResolver(ServiceResult, |
| 222 |
list(globals().values()), key=lambda obj: obj.code) |
| 223 |
|
| 224 |
|
| 225 |
def getFormat(formatName): |
| 226 |
try: |
| 227 |
return _getFormat(formatName) |
| 228 |
except KeyError: |
| 229 |
raise base.ValidationError("Unknown format '%s'."%formatName, |
| 230 |
"_OUTPUT") |
| 231 |
|
| 232 |
|
| 233 |
class OutputFormat(object): |
| 234 |
"""A widget that offers various output options in close cooperation |
| 235 |
with gavo.js and QueryMeta. |
| 236 |
|
| 237 |
The javascript provides options for customizing output that non-javascript |
| 238 |
users will not see. Also, formal doesn't see any of these. See gavo.js |
| 239 |
for details. |
| 240 |
|
| 241 |
This widget probably only makes sense in the Form renderer and thus |
| 242 |
should probably go there. |
| 243 |
""" |
| 244 |
def __init__(self, typeOb, service, queryMeta): |
| 245 |
self.service = service |
| 246 |
self.typeOb = typeOb |
| 247 |
self._computeAvailableFields(queryMeta) |
| 248 |
self._computeAvailableFormats(queryMeta) |
| 249 |
|
| 250 |
def _computeAvailableFormats(self, queryMeta): |
| 251 |
"""sets the availableFormats property. |
| 252 |
|
| 253 |
This is a helper for the constructor, inspecting serviceresults' globals(). |
| 254 |
""" |
| 255 |
outputFields = self.service.getCurOutputFields( |
| 256 |
queryMeta, |
| 257 |
raiseOnUnknown=False) |
| 258 |
self.availableFormats = [ |
| 259 |
(code, format.getLabel()) |
| 260 |
for code, format in _getFormat.registry.items() |
| 261 |
if format.canWrite(outputFields)] |
| 262 |
|
| 263 |
def _computeAvailableFields(self, queryMeta): |
| 264 |
"""computes the fields a Core provides but are not output by |
| 265 |
the service by default. |
| 266 |
|
| 267 |
This of course only works if the core defines its output table. |
| 268 |
Otherwise, availableFields is an empty list. |
| 269 |
""" |
| 270 |
self.availableFields = [] |
| 271 |
core = self.service.core |
| 272 |
if (not core.outputTable |
| 273 |
or self.service.getProperty("noAdditionals", False)): |
| 274 |
return |
| 275 |
coreNames = set(f.name for f in core.outputTable) |
| 276 |
defaultNames = set([f.name |
| 277 |
for f in self.service.getHTMLOutputFields( |
| 278 |
queryMeta, |
| 279 |
ignoreAdditionals=True, |
| 280 |
raiseOnUnknown=False)]) |
| 281 |
|
| 282 |
for key in coreNames-defaultNames: |
| 283 |
try: |
| 284 |
self.availableFields.append((core.outputTable.getColumnByName(key), |
| 285 |
key in queryMeta["additionalFields"])) |
| 286 |
except KeyError: # Core returns fields not in its table, |
| 287 |
# probably computes them |
| 288 |
pass |
| 289 |
|
| 290 |
def _makeAdditionalSelector(self): |
| 291 |
"""returns an ul element containing form material for additional output |
| 292 |
columns. |
| 293 |
""" |
| 294 |
checkLiterals = {True: "checked", False: None} |
| 295 |
fields = [] |
| 296 |
for column, checked in sorted( |
| 297 |
self.availableFields, key=lambda p:p[0].name): |
| 298 |
fields.append(T.tr[ |
| 299 |
T.td[ |
| 300 |
T.input(type="checkbox", name="_ADDITEM", value=column.key, |
| 301 |
style="width:auto", |
| 302 |
checked=checkLiterals[checked])], |
| 303 |
T.td(style="vertical-align:middle")[ |
| 304 |
" %s -- %s"%(column.name, column.description)]]) |
| 305 |
return T.table(id="addSelection")[fields] |
| 306 |
|
| 307 |
def render(self, request, key, args, errors): |
| 308 |
res = T.div(id=render_cssid("_OUTPUT"), style="position:relative")[ |
| 309 |
customwidgets.SelectChoice(formaltypes.String(), |
| 310 |
options=self.availableFormats, |
| 311 |
noneOption=("HTML", "HTML")).render(request, "_FORMAT", args, errors)( |
| 312 |
onchange="output_broadcast(this.value)")] |
| 313 |
|
| 314 |
if self.availableFields: |
| 315 |
res[ |
| 316 |
T.div(title="Additional output column selector", |
| 317 |
id=render_cssid("_ADDITEMS"), |
| 318 |
style="display:none")[ |
| 319 |
self._makeAdditionalSelector()]] |
| 320 |
return res |
| 321 |
|
| 322 |
renderImmutable = render # This is a lost case |
| 323 |
|
| 324 |
def processInput(self, request, key, args): |
| 325 |
return args.get("_FORMAT", ["HTML"])[0] |