def export(req): """ export definition: url contains /[type]/[id] """ if not current_user.is_admin: return httpstatus.HTTP_FORBIDDEN path = req.path[1:].split("/") try: module = findmodule(path[1]) tempfile = join_paths(config.get("paths.tempdir"), str(random.random())) with codecs.open(tempfile, "w", encoding='utf8') as f: try: f.write(module.export(req, path[2])) except UnicodeDecodeError: f.write(module.export(req, path[2]).decode('utf-8')) _sendFile(req, tempfile, u"application/xml", nginx_x_accel_redirect_enabled=False) if os.sep == '/': # Unix? os.unlink( tempfile ) # unlinking files while still reading them only works on Unix/Linux except: logg.info("module has no export method")
def popup_fullsize(self, req): if not self.has_data_access() or not self.has_read_access(): req.write(t(req, "permission_denied")) return document = self.document if document is not None: _sendFile(req, document.abspath, document.mimetype)
def sendZipFile(req, path): tempfile = os.path.join(config.get("paths.tempdir"), unicode(random.random())) + ".zip" zip = zipfile.ZipFile(tempfile, "w") zip.debug = 3 def r(p): if os.path.isdir(os.path.join(path, p)): for file in os.listdir(os.path.join(path, p)): r(os.path.join(p, file)) else: while len(p) > 0 and p[0] == "/": p = p[1:] with suppress(Exception, warn=False): zip.write(os.path.join(path, p), p) r("/") zip.close() req.reply_headers['Content-Disposition'] = "attachment; filename=shoppingbag.zip" _sendFile(req, tempfile, "application/zip", nginx_x_accel_redirect_enabled=False) if os.sep == '/': # Unix? os.unlink(tempfile) # unlinking files while still reading them only works on Unix/Linux
def serve_file(req, path, params, data, filepath): atime = starttime = time.time() d = {} d['timetable'] = [] if 'mimetype' in params: mimetype = params['mimetype'] elif filepath.lower().endswith('.html') or filepath.lower().endswith( '.htm'): mimetype = 'text/html' else: mimetype = getMimeType(filepath) req.reply_headers['Content-Type'] = mimetype if WEBROOT: basedir = WEBROOT else: basedir = os.path.dirname(os.path.abspath(__file__)) abspath = os.path.join(basedir, 'static', filepath) logg.info("web service trying to serve: %s", abspath) if os.path.isfile(abspath): filesize = os.path.getsize(abspath) _sendFile(req, abspath, mimetype, force=1) d['timetable'].append( ["reading file '%s'" % filepath, time.time() - atime]) atime = time.time() d['status'] = 'ok' dataready = "%.3f" % (time.time() - starttime) d['dataready'] = dataready return 200, filesize, d # ok else: d['status'] = 'fail' dataready = "%.3f" % (time.time() - starttime) d['dataready'] = dataready return 404, 0, d # not found
def send_workflow_diagram(req, media_type="png"): """Delivers workflow image, pdf or dot code to client. :param media_type: one of: 'png','svg', 'pdf', 'dot' (...) """ workflow = getWorkflow(req.params.get("wid", "")) diag = GraphvizWorkflowDiagram(workflow) if media_type == "png": diag.render_png() _sendFile(req, diag.filename(media_type), "image/png") elif media_type == "svg": diag.render_svg() _sendFile(req, diag.filename(media_type), "image/svg+xml") elif media_type == "pdf": diag.render_pdf() _sendFile(req, diag.filename(media_type), "application/pdf") elif media_type == "dot": diag.write_dot() _sendFile(req, diag.filename(media_type), "text/vnd.graphviz") else: raise ValueError("media type " + media_type + " not supported!")
def show_printview(req): """ create a pdf preview of given node (id in path e.g. /print/[id].pdf)""" match = RE_PRINT_URL.match(req.path) nodeid = int(match.group(1)) node = q(Node).get(nodeid) if node.system_attrs.get("print") == "0" or not node.has_read_access(): return 404 style = int(req.params.get("style", 2)) # nodetype mtype = node.metadatatype mask = None metadata = None if mtype: for m in mtype.getMasks(): if m.getMasktype() == "fullview": mask = m if m.getMasktype() == "printview": mask = m break if not mask: mask = mtype.getMask("nodebig") if mask: metadata = mask.getViewHTML([node], VIEW_DATA_ONLY + VIEW_HIDE_EMPTY) if not metadata: metadata = [['nodename', node.getName(), 'Name', 'text']] # XXX: use scalar() after duplicate cleanup presentation_file = node.files.filter_by(filetype=u"presentation").first() imagepath = presentation_file.abspath if presentation_file is not None else None # children children = [] if isinstance(node, Container): ret = [] getPrintChildren(req, node, ret) logg.debug("getPrintChildren done") maskcache = {} for c in ret: if not isinstance(c, Container): # items if c.schema in maskcache: c_mask = maskcache[c.schema] else: c_mtype = c.metadatatype c_mask = c_mtype.getMask("printlist") if not c_mask: c_mask = c_mtype.getMask("nodesmall") maskcache[c.schema] = c_mask _c = c_mask.getViewHTML([c], VIEW_DATA_ONLY) if len(_c) > 0: children.append(_c) else: # header items = getPaths(c) if not items: continue p = [] for item in items[0]: p.append(item.getName()) p.append(c.getName()) children.append([(c.id, " > ".join(p[1:]), c.getName(), "header")]) if len(children) > 1: col = [] order = [] try: sort = getCollection(node).get("sortfield") except: logg.exception( "exception in show_printview, getting sortfield failed, setting sort = \"\"" ) sort = "" for i in range(0, 2): col.append((0, "")) order.append(1) if req.params.get("sortfield" + str(i)) != "": sort = req.params.get("sortfield" + unicode(i), sort) if sort != "": if sort.startswith("-"): sort = sort[1:] order[i] = -1 _i = 0 for c in children[0]: if c[0] == sort: col[i] = (_i, sort) _i += 1 if col[i][1] == "": col[i] = (0, children[0][0][0]) # sort method for items def myCmp(x, y, col, order): cx = "" cy = "" for item in x: if item[0] == col[0][1]: cx = item[1] break for item in y: if item[0] == col[0][1]: cy = item[1] break if cx.lower() > cy.lower(): return 1 * order[0] return -1 * order[0] sorted_children = [] tmp = [] for item in children: if item[0][3] == "header": if len(tmp) > 0: tmp.sort(lambda x, y: myCmp(x, y, col, order)) sorted_children.extend(tmp) tmp = [] sorted_children.append(item) else: tmp.append(item) tmp.sort(lambda x, y: myCmp(x, y, col, order)) sorted_children.extend(tmp) children = sorted_children print_dir = [] printfile = printview.getPrintView(lang(req), imagepath, metadata, getPaths(node), style, children, getCollection(node), return_file=True, print_dir=print_dir) _sendFile(req, printfile, "application/pdf", nginx_x_accel_redirect_enabled=False) if print_dir: shutil.rmtree(print_dir[0], ignore_errors=True)
def sendBibFile(req, path): req.reply_headers['Content-Disposition'] = "attachment; filename=export.bib" _sendFile(req, path, getMimeType(path)) if os.sep == '/': # Unix? os.unlink(path) # unlinking files while still reading them only works on Unix/Linux