Here are the examples of the python api bokeh.embed.server_session taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1 Examples
0
View Source File : restservice.py
License : MIT License
Project Creator : smartyal
License : MIT License
Project Creator : smartyal
def all(path):
if path in ["/",""]: path="index.html"
requestStartTime = datetime.datetime.now()
#print("here")
logger.info("http request "+str(flask.request.method) +"'"+str(path)+"'" +" DATA="+str_lim(flask.request.data,200)) # limit to plot max 50 chars
data = None
response="{}" #default is empty
responseCode = 404 # default is not found
try:
try:
#parse the incoming data
if flask.request.data:
try:
data = flask.request.data.decode('utf-8') # just the string
data = json.loads(flask.request.data.decode('utf-8'))
except:
pass
else:
data = {}
except:
pass
#if the path has ending /, we remove it
if path[-1]=='/':
path = path[:-1]
# server all the frontend stuff: js, css etc
if any(extension in str(path) for extension in ['.js','.css','.htm','.img','.ico','.png','.gif','.map','.svg','.wof','.ttf','.pdf']):
logger.debug(" serve html "+ str(path))
if "styles.css" in path:
print("hier")
sourceFolders = ["web","bokeh_web","bokeh_web/templates"]
sourceFolders.extend(plugin_directories)
for sourceFolder in sourceFolders:
try:
obj = flask.send_from_directory(sourceFolder,path)
return obj
except Exception as exc:
#pass
logger.error("file "+ str(path)+" not found on folder"+sourceFolder)
logger.error(f"file {path} not found on folders {sourceFolders}")
code = 404
elif (str(path) == "_getall") and str(flask.request.method) in ["POST","GET"]:
logger.debug("execute getall")
mymodel = m.get_model_for_web()
response = json.dumps(mymodel,indent=4)# some pretty printing for debug
responseCode = 200
elif (str(path) == "_getallhashed") and str(flask.request.method) in ["POST","GET"]:
logger.debug("execute getall hashed")
mymodel = m.get_model_for_web(getHash=True)
response = json.dumps(mymodel,indent=4)# some pretty printing for debug
responseCode = 200
elif (str(path) == "_getbranch") and str(flask.request.method) in ["POST","GET"]:
logger.debug("get branch")
mymodel = m.get_branch(data)
response = json.dumps(mymodel, indent=4) # some pretty printing for debug
responseCode = 200
elif (str(path) == "_getnodes") and str(flask.request.method) in ["POST","GET"]:
logger.debug(f"getnodes")
includeLong = data["includeLongValues"]
key = data["resultKey"]
response = {}
for node in data["nodes"]:
dic=m.get_node_info(node,includeLongValues=includeLong)
if key == "browsePath":
response[m.get_browse_path(node)]=dic
response = json.dumps(response, indent=4) # some pretty printing for debug
responseCode = 200
elif (str(path) == "_getbranchpretty") and str(flask.request.method) in ["POST","GET"]:
logger.debug(f"get branch pretty {data}")
if type(data) is str:
mymodel = m.get_branch_pretty(data)
elif type(data) is dict:
ignore = []
if "ignore" in data:
ignore = data["ignore"]
mymodel= m.get_branch_pretty(data["node"],data["depth"],ignore)
response = json.dumps(mymodel, indent=4) # some pretty printing for debug
responseCode = 200
elif (str(path) == "_getcontextmenu") and str(flask.request.method) in ["POST","GET"]:
logger.debug(f"get branch pretty {data}")
if type(data) is str:
mymodel = m.get_context_menu(data)
response = json.dumps(mymodel, indent=4) # some pretty printing for debug
responseCode = 200
elif (str(path) == "pipelines") and str(flask.request.method) in ["GET"]:
logger.debug("execute get pipelines")
try:
pipelinesNodeIds= m.get_node('root.visualization.pipelines').get_children()
pipelines = {}
for pipeNode in pipelinesNodeIds:
pipelines[pipeNode.get_name()]= {"url":pipeNode.get_child("url").get_property("value")}
response = json.dumps(pipelines,indent=4)# some pretty printing for debug
responseCode = 200
except:
logger.error("I have no pipelines")
responseCode = 404
elif (str(path) == "modelinfo") and str(flask.request.method) in ["GET"]:
logger.debug("get modelinfo")
response = json.dumps(m.get_info(), indent=4)
responseCode = 200
elif (str(path) == "templates") and str(flask.request.method) in ["GET"]:
logger.debug(" get templates")
#we first import from the upload directory (maybe recently changed)
m.import_plugins_from_directory("upload")
templates = list(m.get_templates().keys())
logger.debug(" templates are "+str(templates))
response = json.dumps(templates)
responseCode = 200
elif (str(path) == "models") and str(flask.request.method) in ["GET"]:
logger.debug(" get models")
models = m.get_models()
response = json.dumps(models)
responseCode = 200
elif(str(path) == "_getAnnotations") and str(flask.request.method) in ["POST", "GET"]:
logger.debug("execute get forward")
nodes = m.get_annotations_fast(data)
response = json.dumps(nodes, indent=4)
responseCode = 200
elif(str(path) == "_createAnnotation") and str(flask.request.method) in ["POST", "GET"]:
logger.debug("execute _createAnnotation")
id = m.create_annotation(data)
response = json.dumps(id)
if id:
responseCode = 201
else:
responseCode = 400
elif (str(path) == "_getWidgetView") and str(flask.request.method) in ["POST", "GET"]:
logger.debug("execute get widget view")
response = json.dumps(m.get_widget_view(data["node"],data["version"]))
responseCode = 200
elif (str(path) == "_setWidgetView") and str(flask.request.method) in ["POST", "GET"]:
logger.debug("execute set widget view")
response=""
if m.set_widget_view(data["node"],data["data"]):
responseCode = 200
else:
responseCode = 400
elif (str(path) == "_swapWidgetView") and str(flask.request.method) in ["POST"]:
logger.debug("execute set widget view")
response=""
if m.swap_widget_view(data["from"],data["to"]):
responseCode = 200
else:
responseCode = 400
elif(str(path) == "_getleaves") and str(flask.request.method) in ["POST", "GET"]:
logger.debug("execute get forward")
nodes = m.get_leaves(data)
#additionally, we provide browsepaths for the forward ids of referencers
for node in nodes:
if "forwardRefs" in node:
node["forwardPaths"]=[m.get_browse_path(id) for id in node["forwardRefs"]]
if "children" in node:
for child in node["children"]:
child["forwardPaths"] = [m.get_browse_path(id) for id in child["forwardRefs"]]
response = json.dumps(nodes, indent=4)
responseCode = 200
elif(str(path) == "_delete") and str(flask.request.method) in ["POST"]:
#logger.debug("delete nodes")
result = []
responseCode = 200
for nodePath in data:
delResult = m.delete_node(nodePath)
logger.debug("deleted " +nodePath + " result: "+str(delResult))
result.append(delResult)
if not delResult:
responseCode = 401
response = json.dumps(result, indent=4)
elif (str(path) == "_get") and str(flask.request.method) in ["POST", "GET"]:
logger.debug("execute get"+str(data))
nodes = []
for nodeDesc in data:
resNodes = m.get_node_with_children(nodeDesc)
print(resNodes)
nodes.append(resNodes)
response = json.dumps(nodes, indent=4) # some pretty printing for debug
logger.debug("sending"+str(len(response)))
responseCode = 200
elif (str(path) == "_getvalue") and str(flask.request.method) in ["POST", "GET"]:
#logger.debug("execute getvalue")
values = []
if not type(data) is list:
data = [data]
isList=False
else:
isList = True
try:
for nodeDesc in data:
value = m.get_value(nodeDesc)
if type(value) is numpy.ndarray:
value = list(value)
values.append(value) # a list of lists
if not isList:
values = values[0]
response = json.dumps(values, indent=4) # some pretty printing for debug
except Exception as ex:
logger.error("problem get value",ex )
logger.debug("sending "+str(len(response)))
responseCode = 200
elif (str(path) == "_load") and str(flask.request.method) in ["POST"]:
logger.debug("load model:" + data)
result = m.load(data)
if result:
responseCode = 200
else:
responseCode = 404
elif (str(path) == "_save") and str(flask.request.method) in ["POST"]:
logger.debug("save to model:" + data)
result = m.save(data)
if result:
responseCode = 200
else:
responseCode = 404
elif (str(path) == "_saveModel") and str(flask.request.method) in ["POST","GET"]:
logger.debug("save just the model, this is for debugg/dev:")
result = m.save_model()
if result:
responseCode = 200
else:
responseCode = 404
elif (str(path)=="_insert"):
#logger.debug("insert Blobs")
try:
table = data["table"]
blobs = data["blobs"]
result = m.time_series_insert_blobs(table,blobs)
if not result:
responseCode = 400
else:
responseCode = 201
#m.show()
except Exception as ex:
logger.error("_insert failed" + str(ex) + str(sys.exc_info()[0]))
responseCode = 400
elif (str(path)=="_insertEvents"):
#logger.debug("insert events")
if "delete" in data and data["delete"]== True:
m.event_series_set(data["node"],values=[],times=[])
result = m.event_series_insert_blob(data)
if not result:
responseCode = 400
else:
responseCode = 201
elif (str(path)=="_getEvents"):
#logger.debug("get events data")
filter=start=end= None
if "filter" in data:
filter = data["filter"]
if "start" in data:
start = data["start"]
if "end" in data:
end = data["end"]
if type(data["nodes"]) is list:
result = {}
for node in data["nodes"]:
result[node] = m.event_series_get(node,start=start, end = end, eventFilter=filter,format="events")
else:
node = data["nodes"]
result = m.event_series_get(node,start=start, end = end, eventFilter=filter,format="events")
response = json.dumps(result, indent=4)
responseCode = 200
elif (str(path)=="_getdata"):
#logger.debug("get data")
startTime = None
endTime = None
if set(["bins","nodes"]).issubset(set(data.keys())):
#we have both bins and nodes
startTime = 0
endTime = 0
if "startTime" in data:
#try to parse it, we support iso format or epoch
if type(data["startTime"]) is str:
try:
startTime = dateutil.parser.parse(data["startTime"])
except:
logger.info("cant parse start time")
else:
startTime = data["startTime"]
if "endTime" in data:
#try to parse it, we support iso format or epoch
if type(data["endTime"]) is str:
try:
startTime = dateutil.parser.parse(data["endTime"])
except:
logger.info("cant parse end time")
else:
endTime = data["endTime"]
if "includeTimeStamps" in data:
includeTimeStamps = data["includeTimeStamps"]
else:
includeTimeStamps= None
if "includeBackGround" in data:
includeBackGround = data["includeBackGround"]
else:
includeBackGround = None
if "includeIntervalLimits" in data :#we include one more data point left and right of the actal start and end time
includeIntervalLimits = True
else:
includeIntervalLimits = False
if "includeAllNan" in data:
includeAllNan = data["includeAllNan"]
else:
includeAllNan = False
if "resampleMethod" in data:
resampleMethod = data["resampleMethod"]
else:
resampleMethod = None
try:
#result = m.get_timeseries_table(data["nodes"],startTime=startTime,endTime=endTime,noBins=int(data["bins"]),includeTimeStamps=includeTimeStamps,format="dict",includeBackGround=includeBackGround)
result = m.time_series_get_table(data["nodes"],
start=startTime,
end=endTime,
noBins=int(data["bins"]),
format="flat",
toList=True,
includeIntervalLimits=includeIntervalLimits,
includeAllNan=includeAllNan,
resampleMethod=resampleMethod)
if type(result) != type(None):
if includeTimeStamps:
pass #XXX todo: include the timestamps converted to a certain format
#data["nodes"].append("time")
response = json.dumps(result,indent = 4)
responseCode = 200
else:
responseData = 400
except Exception as ex:
logger.error("get time series tables failed"+str(ex)+str(sys.exc_info()))
responseCode = 404
else:
responseCode = 400 # malformed
elif (str(path) == "_create"):
logger.debug("create ")
result = []
responseCode = 201
for blob in data:
#check if new or modification
id = m.get_id(blob["browsePath"])
if id:
#this is a modification
adjust = m.set_properties(blob)
result.append(id)
else:
targets = []
if "targets" in blob:
targets = blob["targets"]
del blob["targets"]
newNodeId = m.create_node_from_path(blob["browsePath"],blob)
if targets:
m.add_forward_refs(newNodeId,targets)
logger.debug('creating'+blob["browsePath"]+', result:'+str(newNodeId))
result.append(newNodeId)
if not newNodeId:
responseCode = 400
response = json.dumps(result)
responseCode = 201
elif (str(path) == "_setTimeSeries") and str(flask.request.method) in ["POST"]:
logger.debug("set Time Series")
result = {}
for descriptor,series in data["data"].items():
result["descriptor"]=False # default no success
id = m.get_id(descriptor)
if not id:
#this node must be created
id = m.create_node_from_path(descriptor,properties={"type":"timeseries"})
if data["insert"]:
#insert
result["descriptor"] = m.time_series_insert(id, values=series["values"], times=series["__time"], allowDuplicates=False)
else:
#set
result["descriptor"] = m.time_series_set(id,values=series["values"], times=series["__time"])
responseCode = 200
response = json.dumps(result)
elif (str(path) == "_push") and str(flask.request.method) in ["POST"]:
m.push_nodes(data)
responseCode = 201
elif (str(path) == "_createTemplate") and str(flask.request.method) in ["POST"]:
logger.debug("craete Template ")
templates = m.get_templates()
if data["type"] in templates:
m.create_template_from_path(data["browsePath"],templates[data["type"]])
responseCode = 201
else:
responseCode = 404
elif (str(path) == "setProperties"):
#logger.debug("set properties ")
responseCode = 201
result = True
for blob in data:
result = result and m.set_properties(blob)
if not result:
responseCode = 400
elif (str(path) == "setPropertiesQuiet"):
# logger.debug("set properties ")
responseCode = 201
result = True
for blob in data:
result = result and m.set_properties(blob,notify = False)
if not result:
responseCode = 400
elif (str(path) == "_references"):
#logger.debug("set new references")
result = []
m.lock_model()
m.disable_observers() #avoid intermediate events
if "allowDuplicates" in data:
allowDuplicates = data["deleteExisting"]
else:
allowDuplicates = True
if "deleteExisting" in data and data["deleteExisting"] == True:
m.remove_forward_refs(data["parent"])
if "add" in data:
result = m.add_forward_refs(data["parent"],data["add"],allowDuplicates=allowDuplicates)
if "remove" in data:
result = m.remove_forward_refs(data["parent"], data["remove"],deleteDuplicates=True)
m.enable_observers()
m.release_model()
m.notify_observers([m.get_id(data["parent"])],"forwardRefs")
responseCode = 201
elif (str(path) == "_clone"):
logger.debug(f"clone")
m.disable_observers()
result = False
try:
result = m.clone(data["node"])
finally:
m.enable_observers()
m.notify_observers(["1"], "children") #notify the root just to trigger the tree updates
if result:
responseCode = 201
else:
responseCode = 400
elif (str(path) == "_execute"):
logger.debug(f"execute function {str_lim(data,50)} (start the function thread)") #limit the plot to 50
if type(data) is str:
result =[]
launch = m.execute_function(data)
else:
parameter = None
if "parameter" in data:
parameter = data["parameter"]
launch = m.execute_object_function(data["node"],data["function"],parameter)
if launch==True:
responseCode = 200
elif launch == "busy":
responseCode = 429
else:
responseCode = 404
elif (str(path) == "_instantiate"):
logger.debug(f"instantiate {data}")
result = m.instantiate_object(data)
if result:
responseCode = 201
else:
responseCode = 404
elif (str(path) == "_diffUpdate") and str(flask.request.method) in ["GET","POST"]:
if not data or data["handle"] is None:
#this is for creating a handle
curModel = m.get_model_for_web()
handle = m.create_differential_handle()
logger.debug("create new differential update, return handle:"+handle)
res = {"handle":handle,"model":curModel}
response = json.dumps(res)
responseCode = 200
else:
#we have a handle
logger.debug("get differential update with handle:"+data["handle"])
res = m.get_differential_update(data["handle"])
if res:
logger.debug("return diff update from :"+data["handle"]+"=>" + res["handle"]+"data"+json.dumps(res))
response = json.dumps(res)
responseCode = 200
else:
logger.error("requested handle does not exist"+data["handle"])
response ="requested handle does not exist"
responseCode = 404
elif (str(path)=='embedbokeh'):
# here, we must have the correct html file for rendering including css and html coloring
# as the index.html is not relevant anymore
embed = """
< !doctype html>
< body>
< link rel="stylesheet" href="templates/styles.css">
< script>{% include 'moment.min.js.js' %} < /script>
< script>{% include 'moment-timezone-with-data.min.js' %} < /script>
{{ script|safe }}
< /body>
< /html>
"""
app_url = data['url']#'http://localhost:5006/bokeh_web'
try:
if 1==0:
#this is the old style pulling the session, both work only for localhost
with pull_session(url=app_url) as session:
# customize session here
#script = server_session(session_id='12345', url=app_url)
logger.debug("bokeh pull_session done")
script= server_session(session_id=session.id, url=app_url)
logger.debug("bokeh server_session() done")
#script = server_document('http://localhost:5006/bokeh_web')
temp = render_template_string(embed, script=script)
response = temp
responseCode = 200
#return temp
else:
script = server_session(session_id=str(uuid.uuid4().hex), url=app_url)
temp = render_template_string(embed, script=script)
response = temp
responseCode = 200
except Exception as ex:
logger.error("pulling session failed"+str(ex)+str(sys.exc_info()[0]))
responseCode = 404
elif (str(path)=="dropnodes") and str(flask.request.method) in ["POST"]:
logger.debug("dropnodes")
try:
nodeIds = data["nodes"]
#check which type of widget we have to work on
if m.get_node(data["path"]).get_child("widgetType").get_value() == "timeSeriesWidget":
selectNode = m.get_node(data["path"]).get_child("selectedVariables") # pick the referencer from the widget
#also check that the dropped nodes are columns
if type(data["nodes"]) is not list:
data["nodes"]=[data["nodes"]]
newNodesIds = []
for nodeid in data["nodes"]:
if m.get_node_info(nodeid)["type"] not in ["column","timeseries"]:
logger.warning("we ignore this node, is not a colum"+str(nodeid))
else:
newNodesIds.append(m.get_id(nodeid))
#the nodes are columns
logger.debug("now adding new nodes to the widget"+str(newNodesIds))
#first check, if we have this one already, if so, we don't add it again
leaves=selectNode.get_leaves_ids()
newRefs = [id for id in newNodesIds if id not in leaves]
m.add_forward_refs(selectNode.get_id(),newRefs)
responseCode = 201
except Exception as ex:
logger.error("can't add the variables to the widget"+str(ex)+str(sys.exc_info()[0]))
responseCode = 404
elif (str(path)=="move") and str(flask.request.method) in ["POST"]:
logger.debug("move")
try:
moveResult = m.move(data["nodes"],data["parent"])
responseCode = 200
except Exception as ex:
logger.error("can't move"+str(ex)+str(sys.exc_info()[0]))
responseCode = 404
elif (str(path)=="_getlayout") and str(flask.request.method) in ["POST","GET"]:
logger.debug("get layout")
try:
fileName = m.get_value(data['layoutNode'])
with open("web/customui/"+fileName) as fp:
soup = BeautifulSoup(fp, "lxml")
divs = soup.find_all(
id=re.compile("^ui-component")) # find all divs that have a string starting with "ui-component"
for div in divs:
uiinfo = json.loads(div.attrs['uiinfo'])
try:
# now find the widget by looking into the model
widgetType = m.get_node(uiinfo['component'] + '.model').get_leaves()[0].get_child(
"widgetType").get_value()
if widgetType == "timeSeriesWidget":
print("is time series widget")
# this is a bokeh time series widget, so we must do some things here
port = m.get_node(uiinfo['component'] + '.settings').get_value()["port"]
# now get the host under which the client sees me:
host = flask.request.host.split(':')[0]
if not bokehUrl:
script = server_document(url="http://" + host + ":" + str(port) + "/bokeh_web",
relative_urls=False, resources='default',
arguments=None)
else:
bokehPath = "http://" + host+"/"+bokehUrl+"/"+str(listenPort+port-5000)+"/bokeh_web"
script = server_document(url=bokehPath,
relative_urls=False, resources='default',
arguments=None)
if "xhr" in script:
#to detect the bokeh 2.x
div.append(script)
else:
#bokeh 1.4ff
# script = script.encode('utf-8') # due to problem with "&"
scriptHtml = BeautifulSoup(script, "lxml")
scriptTag = scriptHtml.find("script")
scriptSource = scriptTag["src"]
scriptId = scriptTag["id"]
scriptinsert = scriptTag.prettify(formatter=None)
scriptTag = soup.new_tag("script",src=scriptSource,id=scriptId)
div.append(scriptTag)
uiinfo["droppath"] = m.get_node(uiinfo['component'] + '.model').get_leaves()[0].get_browse_path()
div.attrs['uiinfo'] = json.dumps(uiinfo)
else:
logger.error("unsupported widget type" + str(widgetType))
#print(uiinfo)
except Exception as ex:
logger.error(f"can't get layouttt {ex} component" + str(uiinfo['component']))
response = str(soup)
response = response.replace('&', '&') # hack: can't get beautifulsoup to suppress the conversion
response = response.replace('<', ' < ')
response = response.replace('>', '>')
logger.debug(response)
responseCode = 200
except Exception as ex:
logger.error("can't get layout" + str(ex) + str(sys.exc_info()[0]))
responseCode = 404
elif (str(path)=="_setlen") and str(flask.request.method) in ["POST"]:
logger.debug("setlen of column")
result = {}
for descriptor,newLen in data.items():
result[descriptor] = m.set_column_len(descriptor,newLen)
responseCode = 200
response = json.dumps(result)
elif ((str(path)=="_upload") and str(flask.request.method) in ["GET"]):
# Return the files from the upload folder
try:
# get the files from the upload folder
filenames = []
#listdir(mypath)
#for r, d, f in os.walk(UPLOAD_FOLDER):
for filename in os.listdir(UPLOAD_FOLDER):
fullPath=os.path.join(UPLOAD_FOLDER, filename)
if not os.path.isfile(fullPath):
continue
#for filename in f:
filenames.append({
"name": filename,
"time": datetime.datetime.fromtimestamp(
os.path.getmtime(fullPath)).strftime('%Y-%m-%dT%H:%M:%S%z'),
"size": round((float(os.path.getsize(fullPath))/1024)/1024, 3)
})
responseCode = 200
response = json.dumps(filenames)
except Exception as ex:
logger.error("can't retrieve the files from the upload folder: " + str(ex) + str(sys.exc_info()[0]))
responseCode = 404
elif ((str(path) == "_upload") and str(flask.request.method) in ["POST"]):
# Upload a file to the server
try:
# check if the post request has the file part
if 'file' not in request.files:
responseCode = 404
logger.error("File part missing in upload request")
else:
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
responseCode = 404
logger.error("Filename not specified")
else:
filename = secure_filename(file.filename)
file.save(os.path.join(web.config['UPLOAD_FOLDER'], filename))
responseCode = 200
response = "success"
except Exception as ex:
logger.error("Can't save the file to the upload folder: " + str(ex) + str(sys.exc_info()[0]))
responseCode = 404
elif ((str(path) == "_upload") and str(flask.request.method) in ["DELETE"]):
# Upload a file to the server
try:
data = json.loads(flask.request.data.decode('utf-8'))
# check if the post request has the file part
if 'filenames' not in data:
responseCode = 404
logger.error("File part missing in upload request")
else:
# get the list of file names
filesnames = data['filenames']
# if user does not select file, browser also
# submit an empty part without filename
if filesnames == '':
responseCode = 404
logger.error("Filename not specified")
else:
# loop and remove the files
for name in filesnames:
os.remove(web.config['UPLOAD_FOLDER']+"/"+name)
responseCode = 200
response = "deleted successfully"
except Exception as ex:
logger.error("Can't delete the file to the upload folder: " + str(ex) + str(sys.exc_info()[0]))
responseCode = 404
elif ((str(path) == "_downloadfiles") and str(flask.request.method) in ["POST"]):
# Upload a file to the server
try:
data = json.loads(flask.request.data.decode('utf-8'))
# check if the post request has the file part
if 'filenames' not in data:
responseCode = 404
logger.error("File part missing in upload request")
else:
filenames = data['filenames']
# if user does not select file, browser also
# submit an empty part without filename
if filenames == '':
responseCode = 404
logger.error("Filename not specified")
else:
try:
os.remove("./download/myzipfile.zip")
except:
pass
zf = zipfile.ZipFile("./download/myzipfile.zip", "w")
for dirname, subdirs, files in os.walk(web.config['UPLOAD_FOLDER']):
for file in files:
if file in filenames:
zf.write(os.path.join(dirname, file))
zf.close()
# print(flask.send_file(os.path.join(flask.current_app.root_path, 'download', 'myzipfile.zip'), as_attachment=True))
# print(os.walk('./download'))
# responseCode = 200
# response = "files downloaded."
return flask.send_file(os.path.join(flask.current_app.root_path, 'download', 'myzipfile.zip'), as_attachment=True)
# return flask.send_file('/home/techstriker3/workspace/project/21datalab/download/myzipfile.zip', as_attachment=True)
except Exception as ex:
logger.error("Can't download the file to the upload folder: " + str(ex) + str(sys.exc_info()[0]))
responseCode = 404
elif (str(path)=="_refreshauth") and str(flask.request.method) in ["POST"]:
#pick up a cookie if possible
userName = data
if userName:
try:
myPath = os.path.dirname(os.path.realpath(__file__))
f=open(myPath+"/../../users.json") #for now just a file, later we use a db
users = json.loads(f.read())
f.close()
#find the user
cookie = users[userName]["cookie"]
set_cookie(cookie)
logger.info(f"set new cookie for {userName}:{cookie}")
responseCode = 200
except Exception as ex:
set_cookie(None) # no cookie availabe
logger.error(f"cant load cookie from {userName}:{ex}")
responseCode = 404
else:
logger.error("CANNOT HANDLE REQUEST, is unknown"+str(path))
responseCode = 404
timeElapsed = (datetime.datetime.now() - requestStartTime).total_seconds()
logger.info("response on " + str(path) + ": " + str(responseCode) + ", len:" + str( len(response)) + " duration:"+str(timeElapsed))
return flask.Response(response, mimetype="text/html"), responseCode
except Exception as ex:
logger.error("general error " +str(sys.exc_info()[0])+".."+str(ex))
logger.error(m.get_error())
return flask.Response("",mimetype="text/html"),501
if __name__ == '__main__':