def SendFile(self, file): """ Creates the response and sends the file back. Uses the FileIterator. #!date format """ if not file: return HTTPNotFound() last_mod = file.mtime() if not last_mod: last_mod = self.context.meta.pool_change r = Response(content_type=str(GetMimeTypeExtension(file.extension)), conditional_response=True) iterator = file.iterator() if iterator: r.app_iter = iterator else: try: r.body = file.read() except FileNotFound: raise NotFound r.content_length = file.size r.last_modified = last_mod r.etag = '%s-%s' % (last_mod, hash(file.path)) r.cache_expires(self.fileExpires) return r
def MergeFile(req): def DecreaseLarger(arr, n): for i in xrange(len(arr)): if arr[i] > n: arr[i] -= 1 fname = GetQueryFileName(req.GET) links = Reference.FileLinks(fname) try: n = int(req.GET["n"]) except: return HTTPBadRequest_Param("n") try: o = int(req.GET["o"]) except: return HTTPBadRequest_Param("o") for j in links: if n in j.Depends: j.Depends.remove(n) if not o in j.Depends: j.Depends = sorted(j.Depends + [o]) DecreaseLarger(j.Depends, n) for i in xrange(n, len(links) - 1): f = fname + "_" + str(i + 1) if os.path.exists(f): os.rename(f, fname + "_" + str(i)) if o > n: o -= 1 del links.Links[n] links.Write(fname) resp = Response('{"removed":[' + str(n) + '],"select":' + str(o) + ',"files":[' + ",".join(['{"name":"' + os.path.split(l.Name)[1] + '","type":' + str(l.Type) + ',"deps":[' + ",".join([test(d < 65535, str(d), "-1") for d in l.Depends]) + ']}' for l in links]) + ']}\r\n', request=req) resp.cache_expires(0) return resp
def __call__(self): # # find the filename, css files, and format they wanted # filename = params['filename'] || 'RegionReport' # format = params['format'] || 'html' # css_to_include = (params['css'] && params['css'].split(',')) || [] # grab some params filename = self.request.params.get('filename', 'RegionReport') css_inclusions = self.request.params.get('css', '') css_inclusions = css_inclusions.split(',') # start our response response = Response() # use this to write body content to (better than a giant memory-hogging string) body = response.body_file # tell the client this is a downloadable html file response.content_type='application/octet-stream' response.content_disposition='attachment; filename="' + filename + '.html"' response.headers['Content-Desciption'] = 'File Transfer' # unnecessary? # don't cache this file response.cache_expires(0) # sets various cache headers # now start filling out the body body.write("<html><head>\n") # add in the css they wanted for css in css_inclusions: # skip a blank css file (from splitting a blank string, for example) if len(css) == 0: continue # throw away path in case we're being hacked css_file = os.path.join( os.path.dirname(__file__), '..', 'static', 'css', # also replace extension with .css coz SECURITAY os.path.splitext(os.path.basename(css))[0] + '.css' ) css_content = '' try: with file(css_file) as f: css_content = f.read() except IOError: css_content = '/* could not load "' + cgi.escape(css, True) + '" */' body.write("<style>" + css_content + "</style>\n") content = self.request.params.get('content', '(no content was supplied)') content = content.replace( '<img src="/', '<img src="' + self.request.route_url('home') ) body.write("</head><body><div id='report'>\n") body.write(content) body.write("\n</div></body></html>\n") return response
def finish(request, getImage=True): extension = request.matchdict.get("ext", webview_default_image_format) print(f'Got extension: {extension}') if getImage: enter_finish_time = time.time() request.canvas.draw() draw_time = time.time() buffer = BytesIO() p.savefig(buffer, format=extension) end_time = time.time() logger.info("Image rendering: matplotlib %.2fs; %s conversion %.3fs", draw_time - enter_finish_time, extension.upper(), end_time - draw_time) p.close() if getImage: try: r = Response(content_type=CONTENT_TYPES[extension], body=buffer.getvalue()) r.cache_expires(webview_cache_time) return r except KeyError: raise NotImplementedError( 'Tangos does not support the provided image format: ' f'{ext}. ' 'This can be changed in the config.')
def stream(request): response = Response() response.headers.update({'Access-Control-Allow-Origin': '*'}) response.content_type = 'text/event-stream' response.cache_expires(0) response.app_iter = produce() return response
def QueryInitStatus(req): try: f = req.GET["file"] except: return HTTPBadRequest_Param("file") try: i = int(req.GET["id"]) except: return HTTPBadRequest_Param("id") try: alive = Jobs.QueryStatus(f, i) resp = Response(str(alive) + "\r\n", request=req) except HTTPException: raise except: resp = Response("-\r\n", request=req) resp.cache_expires(0) return resp
def _return_file_response(self, value): blob = value['data'] filename = value['name'] mimeType = "application/octet-stream" try: guessed = mimetypes.guess_type(filename, strict=False)[0] if guessed: mimeType = guessed except: pass if isinstance(blob, str): # hmm. no blob image.. (should probably never happen) response = Response(blob, content_type=mimeType) etag = len(blob) elif isinstance(blob, TheBlob): # Can't use FileResponse like this because file might be zipped # get file path.. don't know the proper way to do this.. # but open() sort of works.. #opened_file = blob.open_blob('r') etag = blob._blob._p_mtime #response = FileResponse(opened_file.name, self.request, # content_type=mimeType) response = Response(blob.get(), content_type=mimeType) elif isinstance(blob, Blob): # get file path.. don't know the proper way to do this.. # but open() sort of works.. opened_file = blob.open('r') etag = blob._p_mtime response = FileResponse(opened_file.name, self.request, content_type=mimeType) else: raise "Not a valid file type" # set response caching headers.. response.etag = str(etag) response.cache_expires = (3600 * 24 * 7) cd = u'attachment; filename="{0}"'.format(value['name']) response.content_disposition = cd.encode('utf-8') return response
def download_xml(self): value = self.context.__data__['form'] response = Response(body=value['data'], content_type="text/xml") # set response caching headers.. response.cache_expires = (3600 * 24 * 7) return response
def Upload(req): #uploading from a remote server fs = req.POST.getall("uploadedfiles[]") if platform.system() == "Windows": # Windows has an extra .file in here for some reason for f in fs: if hasattr(f.file, "file"): f.file = f.file.file for f in fs: f.file.seek(0) #Build the index file if not os.path.exists(converted): os.makedirs(converted) try: cleanup = req.POST["delete"] except: cleanup = 7 (jobid, f) = Jobs.add_job("remote", fs, cleanup * 24 * 60 * 60) json_response = '{"file":"' + f + '","jobid":' + str(jobid) + '}\r\n' resp = Response(json_response) resp.cache_expires(0) return resp
def _return_file_response(self, value): blob = value['data'] filename = value['name'] mimeType = "image/png" try: guessed = mimetypes.guess_type(filename, strict=False)[0] if guessed: mimeType = guessed except: pass if isinstance(blob, str): # hmm. no blob image.. (should probably never happen) response = Response(blob, content_type=mimeType) etag = len(blob) elif isinstance(blob, TheBlob): # get file path.. don't know the proper way to do this.. # but open() sort of works.. opened_file = blob.open_blob('r') etag = blob._blob._p_mtime response = FileResponse(opened_file.name, self.request, content_type=mimeType) elif isinstance(blob, Blob): # get file path.. don't know the proper way to do this.. # but open() sort of works.. opened_file = blob.open('r') etag = blob._p_mtime response = FileResponse(opened_file.name, self.request, content_type=mimeType) else: raise "Not a valid image type" # set response caching headers.. response.etag = str(etag) response.cache_expires = (3600 * 24 * 7) return response
def render(self, request): css= request.cache_region.get_or_create('css', self.get_css) response = Response(css) response.content_type = 'text/css' response.cache_expires(3600 * 24) return response
def cssview(self): response = Response(body=css, content_type="text/css") response.cache_expires = 360 return response
def AddFile(req): def DecreaseLarger(arr, n): for i in xrange(len(arr)): if arr[i] > n: arr[i] -= 1 fname = GetQueryFileName(req.GET) links = Reference.FileLinks(fname) try: n = req.GET["n"] ni = int(n) except: return HTTPBadRequest_Param("n") l = links[ni] try: s = req.POST["datas[]"] except: try: s = req.POST["data0"] except: try: s = req.POST["data"] except: return HTTPBadRequest_Param("data") sf = s.file sf.seek(0) t = l.Type & 0x7F if t == Reference.FileType.UNKNOWN: t = TryGet(req.POST, "type") if t != None and int(t) != 0: t = int(t) else: t = Reference.GuessType(sf) if t == Reference.FileType.UNKNOWN: return HTTPUnsupportedMediaType("File type could not be determined") sf.seek(0) sf.seek(0) t2 = Reference.GetTypeParser(t).ToBinary(sf, fname + "_" + n, s.filename) l.Name = s.filename if t2 > t: t = t2 l.Type = t same = TryGet(req.POST, "similar") removed = [] if same != None: same = [int(m) for m in set(same.split(","))] for idx in xrange(len(same)): i = same[idx] for j in links: if i in j.Depends: removed.append(str(i)) j.Depends.remove(i) if not ni in j.Depends: j.Depends = list(set(j.Depends + [ni])) DecreaseLarger(j.Depends, i) if ni > i: ni -= 1 n = str(ni) del links.Links[i] DecreaseLarger(same, i) for i in xrange(i, len(links) - 1): f = fname + "_" + str(i + 1) if os.path.exists(f): os.rename(f, fname + "_" + str(i)) new = Reference.LoadChainGroup([[s.filename, sf]], t) deps_start = len(links) deps_exists = [] added = [] for f in new: if f.Stream != sf: found = False i = 0 for link in links: if link.Name == f.Name: found = True deps_exists.append(i) break i += 1 if not found: if (f.Type & ~Reference.FileType.MISSING) == Reference.FileType.DATABASE: links.AddDB(f.Name) else: added.append(str(len(links))) links.Add(f.Name, f.Type, []) l.Depends = deps_exists + range(deps_start, len(links)) links.Write(fname) resp = Response('{"added":[' + ",".join(added) + '],"removed":[' + ",".join(removed) + '],"select":' + n + ',"files":[' + ",".join(['{"name":"' + os.path.split(l.Name)[1] + '","type":' + str(l.Type) + ',"deps":[' + ",".join([test(d < 65535, str(d), "-1") for d in l.Depends]) + ']}' for l in links]) + ']}\r\n', request=req) resp.cache_expires(0) return resp
def cssview(self): response = Response(body=css, content_type='text/css') response.cache_expires = 360 return response