Debian Codegraph @

gavo/formats/common.py

raw
1 """
2 Common code for generation of various data formats.
3
4 The main function here is formatData. It receives a string format id, a data
5 instance and a destination file (binary mode). It dispatches this to
6 formatters previously registered using registerDataWriter.
7
8 The data writers must take a data instance and a file instance; their
9 effect must be that a serialized representation of data, or, if the format
10 does not support this, the data's primary table is written to the file
11 instance.
12 """
13
14 #c Copyright 2008-2025, the GAVO project <[email protected]>
15 #c
16 #c This program is free software, covered by the GNU GPL. See the
17 #c COPYING file in the source distribution.
18
19
20 import io
21 import os
22 import mimetypes
23
24 from gavo import base
25 from gavo import utils
26
27
28 # used in guessMediaType
29 EXTENSION_FALLBACKS = {
30 ".vot": base.votableType,
31 ".fits": "application/fits",
32 ".fz": "application/fits",
33 }
34
35 # image/fits is probably not quite legal (it's not in Debian's
36 # /etc/mime.types), but it's too handy to pass up
37 mimetypes.add_type("image/fits", ".fits")
38
39
40 class CannotSerializeIn(base.Error):
41 def __init__(self, format):
42 self.format = format
43 base.Error.__init__(self, format,
44 hint="Either you gave an invalid format id or a known format"
45 " did not get registered for some reason. Format codes"
46 " known at this point: %s. You can also try common MIME types"%(
47 ", ".join(FORMATS_REGISTRY.writerRegistry)))
48 self.args = [format]
49
50 def __str__(self):
51 return "Cannot serialize in '%s'."%self.format
52
53
54 def getMIMEKey(contentType):
55 """makes a DaCHS mime key from a content-type string.
56
57 This is used for retrieving matching mime types and is a triple
58 of major and minor mime type and a set of parameter pairs.
59
60 contentType is a string-serialized mime type.
61
62 We also normalise everything to lower case. I don't think that's
63 quite standards-compliant, but with all the other case-insensitivity
64 nonsense, anything else will get really ugly.
65 """
66 contentType = contentType.lower()
67 media_type, paramdict = utils.parseMediaType(contentType)
68 try:
69 major, minor = media_type.split("/")
70 except (ValueError, TypeError):
71 raise CannotSerializeIn(contentType)
72 return (major, minor,
73 frozenset(iter(paramdict.items())))
74
75
76 class FORMATS_REGISTRY(object):
77 """a registry for data formats that can be produced by DaCHS.
78
79 This works by self-registration of the respective modules on their
80 input; hence, if you want to rely on some entry here, be sure
81 there's an import somewhere.
82 """
83 # format key -> writer function
84 writerRegistry = {}
85 # format key -> mime type
86 formatToMIME = {}
87 # format key -> human-readable label
88 formatToLabel = {}
89 # (major, minor, param pair set) -> format key
90 mimeToKey = {}
91 extensionToKey = utils.CaseSemisensitiveDict()
92 keyToExtension = {}
93 # Formats TAPRegExt standard ids have an entry here
94 keyToTAPId = {}
95 # main format key to aliases also accepted
96 keyToAliases = {}
97
98 @classmethod
99 def registerDataWriter(cls,
100 key, writer, mainMime, label, extension, *aliases, tapId=None):
101 """adds a writer to the formats registry.
102
103 Key is a short, unique handle for the format, writer is a writer
104 function(data, outputFile) -> None (where data can be an rsc.Data
105 or an rsc.Table instance), mainMime is the preferred media type,
106 label is a human-readable designation for the format (shown in
107 selection widgets and the like), extension is a suggested extension
108 for the format (lower-case only), and aliases are other strings
109 that can be used to select the format in DALI FORMAT or similar.
110
111 Where keys, mainMime, and aliases clash, previous entries are
112 silently overwritten. For extensions, the first registered format
113 wins.
114 """
115 cls.writerRegistry[key] = writer
116 cls.formatToMIME[key] = mainMime
117 cls.formatToLabel[key] = label
118
119 cls.mimeToKey[getMIMEKey(mainMime)] = key
120 for mime in aliases:
121 cls.mimeToKey[getMIMEKey(mime)] = key
122 if extension not in cls.extensionToKey:
123 cls.extensionToKey[extension] = key
124 cls.keyToExtension[key] = extension
125
126 if tapId is not None:
127 cls.keyToTAPId[key] = tapId
128 cls.keyToAliases[key] = list(aliases)
129 if mainMime!=key:
130 cls.keyToAliases[key].append(key)
131
132 @classmethod
133 def getMIMEFor(cls, formatName, orderedFormat=None):
134 """returns a simple MIME type for our formatName (some incoming MIME
135 or an alias).
136
137 Some magic, reserved mimes that need to be preserved from
138 the input are recognised and returned in orderedFormat. This
139 is for TAP and related DALI hacks.
140 """
141 # TAP Spec, 2.7.1, similar in DALI, wants us to keep some
142 # media types. It's not quite clear which these actually are,
143 # but I'd guess something like:
144 if (orderedFormat
145 and (orderedFormat.startswith("text/xml")
146 or orderedFormat.startswith("application/x-votable+xml")
147 or orderedFormat.startswith("text/plain"))):
148 return orderedFormat
149
150 if formatName in cls.formatToMIME:
151 return cls.formatToMIME[formatName]
152
153 # if it looks like a mime type, return it, otherwise assume it's
154 # an unimported format and return a generic mime
155 if "/" in formatName:
156 return formatName
157 else:
158 return "application/octet-stream"
159
160 @classmethod
161 def getWriterFor(cls, formatName):
162 """returns a writer for formatName.
163
164 writers are what's registered via registerDataWriter; formatName is
165 a MIME type or a format alias. This raises CannotSerializeIn
166 if no writer is available.
167 """
168 return cls.writerRegistry[cls.getKeyFor(formatName)]
169
170 @classmethod
171 def getLabelFor(cls, formatName):
172 """returns a label for formatName (DaCHS key or MIME type).
173 """
174 return cls.formatToLabel[cls.getKeyFor(formatName)]
175
176 @classmethod
177 def getKeyFor(cls, formatName):
178 """returns a DaCHS format key for formatName (DaCHS key or MIME).
179
180 If formatName is a mime type with parameters, we'll also try
181 to get a format with the parameters stripped and silently succeed
182 if that works.
183 """
184 formatName = formatName.lower()
185 if formatName in cls.writerRegistry:
186 return formatName
187
188 try:
189 parsed = getMIMEKey(formatName)
190 if parsed in cls.mimeToKey:
191 return cls.mimeToKey[parsed]
192 parsed = (parsed[0], parsed[1], frozenset())
193 if parsed in cls.mimeToKey:
194 return cls.mimeToKey[parsed]
195 except Exception:
196 raise base.ui.logOldExc(CannotSerializeIn(formatName))
197
198 raise CannotSerializeIn(formatName)
199
200 @classmethod
201 def getAliasesFor(cls, formatName):
202 """returns alternate names for a DaCHS format key.
203
204 Don't modify what you get back. This will return the DaCHS format
205 key if it is not the mime itself.
206 """
207 return cls.keyToAliases[formatName]
208
209 @classmethod
210 def getTAPIdFor(cls, formatName):
211 """returns a TAPRegExt ivoid for a DaCHS format key.
212
213 This will return None if TAPRegExt does not prescribe such a key.
214 """
215 return cls.keyToTAPId.get(formatName)
216
217 @classmethod
218 def getTypeForExtension(cls, extension):
219 """returns the media type first registered for extension.
220
221 extension must begin with a dot. None is returned for extensions
222 no format has (yet) claimed.
223 """
224 key = cls.extensionToKey.get(extension.lower())
225 if key is None:
226 return None
227 return cls.formatToMIME[key]
228
229 @classmethod
230 def iterFormats(cls):
231 """iterates over the short names of the available formats.
232 """
233 return iter(cls.writerRegistry)
234
235
236 registerDataWriter = FORMATS_REGISTRY.registerDataWriter
237 getMIMEFor = FORMATS_REGISTRY.getMIMEFor
238 getKeyFor = FORMATS_REGISTRY.getKeyFor
239 getWriterFor = FORMATS_REGISTRY.getWriterFor
240 getLabelFor = FORMATS_REGISTRY.getLabelFor
241 getAliasesFor = FORMATS_REGISTRY.getAliasesFor
242 getTAPIdFor = FORMATS_REGISTRY.getTAPIdFor
243 iterFormats = FORMATS_REGISTRY.iterFormats
244
245
246 def formatData(
247 formatName,
248 table,
249 outputFile,
250 acquireSamples=True,
251 **moreFormatterArgs):
252 """writes a table to outputFile in the format given by key.
253
254 Table may be a table or a ``Data`` instance. ``formatName`` is a format
255 shortcut (``formats.iterFormats()`` gives keys available) or a media type.
256 If you pass None, the default VOTable format will be selected.
257
258 This raises a ``CannotSerializeIn`` exception if ``formatName`` is
259 not recognized. Note that you have to import the serialising modules
260 from the format package to make the formats available (fitstable,
261 csvtable, geojson, jsontable, texttable, votable; api itself already
262 imports the more popular of these).
263
264 If a client knows a certain formatter understands additional arguments,
265 it can hand them in as keywords arguments. This will raise an error
266 if another formatter that doesn't understand the argument is being used.
267 """
268 if formatName is None:
269 formatName = base.votableType
270 getWriterFor(formatName)(
271 table,
272 outputFile,
273 acquireSamples=acquireSamples,
274 **moreFormatterArgs)
275
276
277 def getFormatted(formatName, table, acquireSamples=False):
278 """returns a string containing a representation of table in the
279 format given by formatName.
280
281 This is just wrapping the `function formatData`_; se there for formatName.
282 This function will use large amounts of memory for large data.
283 """
284 buffer = io.BytesIO()
285 formatData(formatName, table, buffer, acquireSamples)
286 return buffer.getvalue()
287
288
289 def guessMediaType(fName):
290 """returns a media type plausible for a file named fName.
291
292 This first uses the extension map inferred by our formats registry,
293 has some built-in safety catches in case the formatters haven't
294 been imported, and then falls back to built-in python
295 mimetypes.guess_type If nothing matches, it returns
296 application/octet-stream.
297
298 Extensions are used case-insensitively. We don't do any encoding
299 inference (yet). We may, though, so by all means shout if you're using
300 this in DaCHS-external code.
301 """
302 extension = os.path.splitext(fName)[-1].lower()
303 res = FORMATS_REGISTRY.getTypeForExtension(extension)
304
305 if res is None:
306 res = EXTENSION_FALLBACKS.get(extension)
307
308 if res is None:
309 res, _ = mimetypes.guess_type(fName)
310
311 if res is None:
312 res = "application/octet-stream"
313
314 return res
315
316
317 def getExtensionFor(mediaType):
318 """returns a suggested extension for files of mediaType.
319
320 mediaType can be an RFC 2045 media type, or one of DaCHS' internal format
321 codes.
322
323 As a fallback, .dat will be returned.
324 """
325 try:
326 return FORMATS_REGISTRY.keyToExtension[
327 FORMATS_REGISTRY.getKeyFor(mediaType)]
328 except (CannotSerializeIn, KeyError):
329 return mimetypes.guess_extension(mediaType) or ".dat"