Commit ee79977d authored by Caillat Michel's avatar Caillat Michel
Browse files

Achieved a first working version of a new REST API : artemix/getDataBlockInfos

parent 29354bff
......@@ -25,6 +25,8 @@ import dask.array as da
import traceback
from datetime import datetime
import os
import re
from functools import reduce
from matplotlib import pyplot as pp
def cmap2palette (palette_name):
......@@ -63,6 +65,9 @@ class DataBlock:
"default_vmode_index" : 0
}
# A regulare expression to catch the NAXISn
__naxisn_rexp = re.compile("NAXIS[1-9]")
#===========================================================================
# Class methods - Setters and getters
@classmethod
......@@ -97,6 +102,16 @@ class DataBlock:
def getRenderingCapabilities(cls):
return DataBlock.__renderingCapabilities
@classmethod
def convert_size(cls, size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
#===========================================================================
# CTOR
#
......@@ -113,7 +128,7 @@ class DataBlock:
self.__convert = None
self.__cdelt = None
self.__timestamp = None # the last time a method was called on self
self.__creationTime = None # the date of birth
self.__logger.debug("A DataBlock has been just built")
#===========================================================================
......@@ -155,7 +170,7 @@ class DataBlock:
self.__header = hdu_list[0].header
#
# Complete the Header if necessary
# Header "normalization"
#
if "TELESCOP" not in self.__header :
self.__header["TELESCOP"] = "Unknown"
......@@ -219,6 +234,9 @@ class DataBlock:
self.__relFITSFilePath = relFITSFilePath
# date of birth == timestamp == now
self.__timestamp = self.__creationTime = datetime.now()
d = dict(self.__header)
result = {"status": True, "message": "", "result":json.dumps(d)}
except Exception as e:
......@@ -874,6 +892,20 @@ class DataBlock:
result.append(self.degToHMSDMS(0, i).split(" ")[1])
self.__logger.debug("rangeToDMS : exiting")
return {"status": True, "message": "", "result": result}
def getDataBlockInfos(self):
valuesOfInterest = [self.__header[key] for key in self.__header if DataBlock.__naxisn_rexp.match(key)]
numberOfPixels = reduce(lambda x, y: x*y, valuesOfInterest)
dimensions = reduce(lambda x, y : "%sx%s"%(x,y), valuesOfInterest)
numberOfBytes = numberOfPixels * abs(self.__header["BITPIX"]/8)
result = {
"path": self.__relFITSFilePath,
"creationTime": self.__creationTime.strftime("%m/%d/%Y, %H:%M:%S"),
"lastAccess": self.__timestamp.strftime("%m/%d/%Y, %H:%M:%S"),
"dimensions": dimensions,
"size": DataBlock.convert_size(numberOfBytes)
}
return result
#
# End of DataBlock class definition.
#
......@@ -18,7 +18,6 @@ import matplotlib as mpl
import png
from PIL import Image, PngImagePlugin
import math
import dask
import dask.array as da
......@@ -96,16 +95,6 @@ class DataManagerImpl :
self.__logger.debug("__checkPresence : exiting")
return result
def __convert_size(self, size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
def __getEntries_0(self, relKey):
self.__logger.debug("__getEntries_0: entering")
try :
......@@ -126,7 +115,7 @@ class DataManagerImpl :
d["folder"] = os.path.isdir(p)
d["lazy"] = d["folder"]
if entry.endswith(".fits") :
size = self.__convert_size(os.path.getsize(p))
size = DataBlock.convert_size(os.path.getsize(p))
d["title"] = "<a href = 'visit/?path=%s/%s' target = '_blank'>%s %s</a>" % (relKey, entry, entry, size)
else:
d["title"] = entry
......@@ -164,13 +153,11 @@ class DataManagerImpl :
#
def setData(self, relFITSFilePath):
self.__logger.debug("setData : entering")
self.__logger.debug(f"relFITSFilePath = {relFITSFilePath}")
result = None
if relFITSFilePath in self.__dataBlocks :
self.__logger.debug("File already opened: %s" % relFITSFilePath)
result = {"status": True, "message": "", "result":json.dumps(dict(self.__dataBlocks[relFITSFilePath].header()))}
else :
self.__logger.debug(f"loading {relFITSFilePath}")
db = DataBlock(self.__logger)
result = db.setData(relFITSFilePath)
if (result["status"]):
......@@ -356,13 +343,10 @@ class DataManagerImpl :
# Return the list of defined DataBlock s sorted ( asc or desc ) by timestamp
#
def getDataBlockInfos(self, reverse=True):
keys = self.__getKeysOrderedByTimestamp(reverse)
result = [
{"path": key,
"lastAccess": datetime.frometimestamp(self.__dataBlocks[key].getTimestamp()).strftime("%m/%d/%Y, %H:%M:%S"),
"size": self.__convert_size(os.path.getsize(FITSFilePrefix + "/" + key))}
]
return {"status": True, message: "", "result": result}
self.__logger.debug("getDataBlockInfos : entering")
result = [self.__dataBlocks[k].getDataBlockInfos() for k in self.__dataBlocks]
self.__logger.debug("getDataBlockInfos : exiting")
return {"status": True, "message": "", "result": result}
#
#
......
......@@ -533,14 +533,23 @@ def getEntries() :
@route( baseUrl+'/renderingCapabilities', name='renderingCapabilities', method='GET')
@enable_cors
def renderingCapabilities():
logger.debug("renderingCapabilities : entering")
logger.debug("renderingCapabilities wrapper : entering")
response.content_type = "application/json; charset=utf-8"
try :
ret = dm.renderingCapabilities()
except Exception as e:
ret = {"result": False, "message": "%s"%e, "result": None}
logger.debug("renderingCapabilities : exiting")
return json.dumps(ret)
result = dm.renderingCapabilities()
logger.debug("renderingCapabilities wrapper : exiting")
return json.dumps(result)
"""
Returns a collection of informations about the DatBlocks present
in memory at the time of the call.
"""
@route( baseUrl+'/getDataBlockInfos', name='getDataBlockInfos', method='GET')
@enable_cors
def getDataBlockInfos():
logger.debug("getDataBlockInfos wrapper : entering")
result = dm.getDataBlockInfos()
logger.debug("getDataBlockInfos wrapper : exiting")
return json.dumps(result)
#
# End of the class
......@@ -570,7 +579,7 @@ def main(argv):
if opt in ('-p', '--port'):
port = int(arg)
logger = logging.getLogger('serverWsgi.michel')
logger = logging.getLogger('serverWsgi.michel.new')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment