def export(self, extm, params, req): csv_dialect = params.pop('csv_dialect', 'excel') csv_encoding = params.pop('csv_encoding', 'utf_8') fields = [] for field in extm.export_view: if isinstance(field, PseudoColumn): continue fields.append(field) if csv_encoding not in _encodings: raise ValueError('Unknown encoding specified') res = Response() loc = get_localizer(req) now = datetime.datetime.now() res.last_modified = now if csv_dialect in ('excel', 'excel-tab'): res.content_type = 'application/vnd.ms-excel' else: res.content_type = 'text/csv' res.charset = _encodings[csv_encoding][0] res.cache_control.no_cache = True res.cache_control.no_store = True res.cache_control.private = True res.cache_control.must_revalidate = True res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN')) if PY3: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.csv' % ( urllib.parse.quote(loc.translate(extm.menu_name), ''), now.date().isoformat() ) else: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.csv' % ( urllib.quote(loc.translate(extm.menu_name).encode(), ''), now.date().isoformat() ) for prop in ('__page', '__start', '__limit'): if prop in params: del params[prop] data = extm.read(params, req)['records'] res.app_iter = csv_generator( data, fields, csv_dialect, encoding=csv_encoding, localizer=loc, model=extm ) return res
def export(self, extm, params, req): csv_dialect = params.pop('csv_dialect', 'excel') csv_encoding = params.pop('csv_encoding', 'utf_8') fields = [] for field in extm.export_view: if isinstance(field, PseudoColumn): continue fields.append(field) if csv_encoding not in csv_encodings: raise ValueError('Unknown encoding specified') res = Response() loc = req.localizer now = datetime.datetime.now() res.last_modified = now if csv_dialect in ('excel', 'excel-tab'): res.content_type = 'application/vnd.ms-excel' else: res.content_type = 'text/csv' res.charset = csv_encodings[csv_encoding][0] res.cache_control.no_cache = True res.cache_control.no_store = True res.cache_control.private = True res.cache_control.must_revalidate = True res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN')) if PY3: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.csv' % ( urllib.parse.quote(loc.translate(extm.menu_name), ''), now.date().isoformat() ) else: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.csv' % ( urllib.quote(loc.translate(extm.menu_name).encode(), ''), now.date().isoformat() ) for prop in ('__page', '__start', '__limit'): if prop in params: del params[prop] data = extm.read(params, req)['records'] res.app_iter = csv_generator(data, fields, csv_dialect, encoding=csv_encoding, localizer=loc, model=extm) return res
def post(self): rows = self.session.query('cid', 'cname', 'uid', 'uemail', 'date', 'time').from_statement(""" SELECT c.id as cid, c.name as cname, u.id as uid, u.email as uemail, date_trunc('month', t.date) as date, SUM(t.time) as time FROM time_entry t, project p, client c, "user" u WHERE t.project_id = p.id AND p.client_id = c.id AND t.user_id = u.id AND t.deleted = false GROUP BY c.id, c.name, u.id, u.email, date_trunc('month', t.date) ORDER BY date_trunc('month', t.date) """).all() monthly = h.groupby(rows, lambda row: (row[2], row[-2]), lambda row: row[5]) rows = [( row[1], row[3], row[5], row[4].strftime('%Y-%m-%d'), sum(monthly[row[2], row[-2]]), ) for row in rows] stream = self._to_excel(rows) response = Response( content_type='application/vnd.ms-excel', app_iter=stream, ) response.headers['Cache-Control'] = 'no-cache' response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now( ).strftime('%d-%m-%Y--%H-%M-%S') return response
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 rdf_conceptscheme_export_turtle(self): graph = utils.rdf_conceptscheme_dumper(self.provider) response = Response(content_type='text/turtle') response.body = graph.serialize(format='turtle') response.content_disposition = 'attachment; filename="%s.ttl"' % (str( self.scheme_id), ) return response
def get_reporting_instance_usage_file(self): conn = self.get_connection(conn_type='ec2reports') if not self.is_csrf_valid(): return JSONResponse(status=400, message="missing CSRF token") granularity = self.request.params.get('granularity') group_by = self.request.params.get('groupBy') dates = self.dates_from_params(self.request.params) filters = self.request.params.get('filters') or '[]' filters = json.loads(filters) with boto_error_handler(self.request): # use "ViewInstanceUsageReport" call to fetch usage information ret = conn.view_instance_usage_report( dates.from_date, dates.to_date, filters, group_by, report_granularity=granularity ) filename = 'EucalyptusInstanceUsage-{0}-{1}-{2}.csv'.format( self.request.session.get('account'), dates.from_date, dates.to_date ) response = Response(content_type='text/csv') response.text = ret.get('usageReport') response.content_disposition = 'attachment; filename="{name}"'.format(name=filename) response.cache_control = 'no-store' response.pragma = 'no-cache' return response
def dump_entries_to_excel(entries, group_by, bigger_than): wbk = xlwt.Workbook() sheet = wbk.add_sheet('Hours') heading_xf = xlwt.easyxf('font: bold on; align: wrap on, vert centre, horiz center') headings = ('Client', 'Project', 'Ticket id', 'Employee', 'Description', 'Date', 'Time') headings_width = (x*256 for x in (20, 30, 10, 40, 100, 12, 10)) for colx, value in enumerate(headings): sheet.write(0, colx, value, heading_xf) for i, width in enumerate(headings_width): sheet.col(i).width = width sheet.set_panes_frozen(True) sheet.set_horz_split_pos(1) sheet.set_remove_splits(True) rows, asum = ExcelRow.from_ordered_data(entries, group_by, bigger_than) for j, row in enumerate(rows): row = row.pprint_row() for i, cell in enumerate(row): sheet.write(j+1, i, *cell) file_path = '/tmp/tmp.xls' wbk.save(file_path) file = open(file_path, 'rb') response = Response( content_type='application/vnd.ms-excel', app_iter = file, ) response.headers['Cache-Control'] = 'no-cache' response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime('%d-%m-%Y--%H-%M-%S') return file, response
def translation_template(request): resp = Response() resp.content_disposition = 'attachment; filename=oscad.pot' resp.app_iter = resource_stream('oscad', 'locale/oscad.pot') # otherwise Firefox thinks its a PowerPoint resp.content_type = 'text/plain' return resp
def dump_entries_to_excel(entries, group_by, bigger_than): wbk = xlwt.Workbook() sheet = wbk.add_sheet("Hours") heading_xf = xlwt.easyxf("font: bold on; align: wrap on, vert centre, horiz center") headings = ("Client", "Project", "Ticket id", "Employee", "Description", "Date", "Time") headings_width = (x * 256 for x in (20, 30, 10, 40, 100, 12, 10)) for colx, value in enumerate(headings): sheet.write(0, colx, value, heading_xf) for i, width in enumerate(headings_width): sheet.col(i).width = width sheet.set_panes_frozen(True) sheet.set_horz_split_pos(1) sheet.set_remove_splits(True) rows, asum = ExcelRow.from_ordered_data(entries, group_by, bigger_than) for j, row in enumerate(rows): row = row.pprint_row() for i, cell in enumerate(row): sheet.write(j + 1, i, *cell) file_path = "/tmp/tmp.xls" wbk.save(file_path) file = open(file_path, "rb") response = Response(content_type="application/vnd.ms-excel", app_iter=file) response.headers["Cache-Control"] = "no-cache" response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime( "%d-%m-%Y--%H-%M-%S" ) return file, response
def rdf_conceptscheme_export(self): graph = utils.rdf_conceptscheme_dumper(self.provider) response = Response(content_type='application/rdf+xml') response.body = graph.serialize(format='xml') response.content_disposition = 'attachment; filename="%s.rdf"' % (str( self.scheme_id), ) return response
def download_roster(self): fieldnames = [ 'last_name', 'first_name', 'grade', 'school', 'experience', 'tourneys', 'emails', 'guardian1_name', 'guardian1_emails'] output = StringIO() writer = DictWriter(output, fieldnames=fieldnames) headers = dict((n, n) for n in fieldnames) writer.writerow(headers) for player in self.context.players(): g1 = player.guardians()[0] g1_last_name = g1.last_name g1_first_name = g1.first_name g1_title = g1.title g1_emails = ','.join(g1.emails) writer.writerow(dict( last_name=player.last_name, first_name=player.first_name, grade=player.props['grade'], school=player.props['school'], experience=player.props['years_experience'], tourneys='/'.join(player.tourneys()), emails=', '.join(player.emails), guardian1_name=g1_title, guardian1_emails=g1_emails )) fn = self.context.__name__ + '-roster.csv' res = Response(content_type='text/csv', ) res.content_disposition = 'attachment;filename=%s' % fn res.body = output.getvalue() return res
def generate_xlsx_response(data, filename): resp = Response() resp.body = data resp.headerlist.append(('Access-Control-Allow-Origin', '*')) resp.content_type = 'application/vnd.ms-excel; charset=utf-8-sig' resp.content_disposition = 'attachment; filename=%s' % filename return resp
def post(self): rows = self.session.query('cid', 'cname', 'uid', 'uname', 'date', 'time').from_statement(""" SELECT c.id as cid, c.name as cname, u.id as uid, u.name as uname, date_trunc('month', t.date) as date, SUM(t.time) as time FROM time_entry t, project p, client c, "user" u WHERE t.project_id = p.id AND p.client_id = c.id AND t.user_id = u.id AND t.deleted = false GROUP BY c.id, c.name, u.id, u.name, date_trunc('month', t.date) ORDER BY date_trunc('month', t.date) """).all() monthly = h.groupby(rows, lambda row: (row[2], row[-2]), lambda row: row[5]) rows = [( row[1], row[3], row[5], row[4].strftime('%Y-%m-%d'), sum(monthly[row[2], row[-2]]), ) for row in rows] stream = self._to_excel(rows) response = Response( content_type='application/vnd.ms-excel', app_iter=stream, ) response.headers['Cache-Control'] = 'no-cache' response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime('%d-%m-%Y--%H-%M-%S') return response
def image(self, subpath=None): """Return the image in a specific scale, either inline (default) or as attachment. :param subpath: [<image_scale>]/download] (optional). When 'download' is the last element in subpath, the image is served with a 'Content-Disposition: attachment' header. <image_scale> has to be one of the predefined image_scales - either from the defaults in this module or one set with a kotti.image_scales.<scale_name> in your app config ini file. :type subpath: str :result: complete response object :rtype: pyramid.response.Response """ if subpath is None: subpath = self.request.subpath width, height = (None, None) subpath = list(subpath) if (len(subpath) > 0) and (subpath[-1] == "download"): disposition = "attachment" subpath.pop() else: disposition = "inline" if len(subpath) == 1: scale = subpath[0] if scale in image_scales: # /path/to/image/scale/thumb width, height = image_scales[scale] if not (width and height): return self.request.uploaded_file_response( self.context.data, disposition) image, format, size = scaleImage(self.context.data.file.read(), width=width, height=height, direction="thumb") res = Response( headerlist=[ ('Content-Disposition', '{0};filename="{1}"'.format( disposition, self.context.filename.encode('ascii', 'ignore'))), ('Content-Length', str(len(image))), ('Content-Type', str(self.context.mimetype)), ], body=image, ) res.content_disposition = rfc6266.build_header( self.context.filename, disposition=disposition, filename_compat=unidecode(self.context.filename)) return res
def backups_export(request): passwords = get_user_passwords(request.user) data = compress(passwords) response = Response(body=data, content_type='application/yith-library') today = datetime.date.today() filename = get_backup_filename(today) response.content_disposition = 'attachment; filename=%s' % filename return response
def csv_download(request): """ CSV Download of vocabulary """ context = get_global_store()[request.matchdict['id']] retval = Response(context.export_as_csv()) retval.content_disposition = 'attachment; filename="%s.csv"' % \ request.context.__name__ retval.content_type = 'application/octet-stream' return retval
def download_wiki_archive(self): archiver = WikiArchiver(self.request.db) archiver.create_new_zipfile() archive = archiver.archive_pages() content_type = 'application/zip' r = Response(content_type=content_type, body=archive) r.content_disposition = 'attachment; filename="tutwiki-archive.zip"' self.response = r
def backups_export(request): passwords = get_user_passwords(request.db, request.user) data = compress(passwords) response = Response(body=data, content_type='application/yith-library') today = datetime.date.today() filename = get_backup_filename(today) response.content_disposition = 'attachment; filename=%s' % filename return response
def __call__(self): response = Response() response.content_disposition = 'attachment; filename="{}"'.format(self.context.filename) response.charset = 'utf-8' response.content_type = self.context.content_type response.body_file = self.context.content.open() response.content_length = self.context.size return response
def _make_response(content, content_type, status, file_name=None): """ Custom response function that is called by pyexcel-webio """ response = Response(content, content_type=content_type, status=status) if file_name: response.content_disposition = "attachment; filename=%s" % (file_name) return response
def job_preset(request): id = request.matchdict['job'] session = DBSession() job = session.query(Job).get(id) response = Response() response.text = job.josm_preset response.content_disposition = 'attachment; filename=hotosm_tasking_manager_job_%s.xml' % job.id response.content_type = 'application/x-josm-preset' return response
def download_wiki_archive(self): self._set_menu() archiver = WikiArchiver(self.request.db) archiver.create_new_zipfile() archive = archiver.archive_pages() content_type = 'application/zip' r = Response(content_type=content_type, body=archive) r.content_disposition = 'attachment; filename="tutwiki-archive.zip"' self.response = r
def export_document(self): id = self.request.matchdict['id'] id = datetime.strptime(id, dt_isoformat) doc = self.sdm.get(id) r = Response(content_type='application/pdf', body=doc.file.content) filename = doc.name r.content_disposition = 'attachment; filename="%s"' % filename self.response = r
def zip2(context, request): out = StringIO() with zipfile.ZipFile(out, 'w') as buildout: for bfile in context.keys(): buildout.writestr(bfile.encode('utf-8'), context[bfile].data.encode('utf-8')) out.seek(0) response = Response(out.getvalue()) response.content_type = 'application/zip' response.content_disposition = "attachment; filename=buildout.zip" return response
def project_preset(request): id = request.matchdict['project'] project = DBSession.query(Project).get(id) response = Response() response.text = project.josm_preset response.content_disposition = \ 'attachment; filename=hotosm_tasking_manager_project_%s.xml' \ % project.id response.content_type = 'application/x-josm-preset' return response
def FileView(request): # pylint: disable=invalid-name """Default file view""" context = request.context # set content type content_type = context.content_type if isinstance(content_type, bytes): content_type = content_type.decode('utf-8') # check for last modification date response = Response(content_type=content_type) zdc = IZopeDublinCore(context, None) if zdc is not None: modified = zdc.modified if modified is not None: if_modified_since = request.if_modified_since # pylint: disable=no-member if if_modified_since and \ (int(modified.timestamp()) <= int(if_modified_since.timestamp())): return Response(content_type=content_type, status=NOT_MODIFIED) response.last_modified = modified body_file = context.get_blob(mode='c') if request.params.get('dl') is not None: filename = context.filename or 'noname.txt' response.content_disposition = 'attachment; filename="{0}"'.format( translate_string(filename, force_lower=False)) # check for range request if request.range is not None: try: body = body_file.read() body_length = len(body) range_start = request.range.start or 0 if 'Firefox' in request.user_agent: # avoid partial range for Firefox videos range_end = body_length else: range_end = request.range.end or min( body_length, range_start + MAX_RANGE_LENGTH) ranged_body = body[range_start:range_end] response.status = PARTIAL_CONTENT response.headers[ 'Content-Range'] = 'bytes {first}-{last}/{len}'.format( first=range_start, last=range_start + len(ranged_body) - 1, len=body_length) response.body = ranged_body finally: body_file.close() else: response.body_file = body_file return response
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 file_download(request): session = request.session if session.get('file_cache'): (filename, mime_type, contents) = session['file_cache'] # Clean the session information regrading the new keypair del session['file_cache'] response = Response(content_type=mime_type) response.body = str(contents) response.content_disposition = 'attachment; filename="{name}"'.format(name=filename) return response # this isn't handled on on client anyway, so we can return pretty much anything return Response(body='BaseView:file not found', status=500)
def _make_response(file_path): res = Response(content_type=_get_mimetype(file_path), conditional_response=True) res.app_iter = FileIterable(file_path) res.content_length = os.path.getsize(file_path) res.last_modified = os.path.getmtime(file_path) res.etag = '{0}-{1}-{2}'.format(os.path.getmtime(file_path), os.path.getsize(file_path), hash(file_path)) filename = os.path.basename(file_path) res.content_disposition = 'attachment; filename={0}'.format(filename) return res
def export(self): exch = Exchange(Base.metadata, ignlist=['cpu_types', 'machine_types', 'nic_types']) fp = StringIO.StringIO() exch.export_xml() exch.write_xml(fp) resp = Response() resp.headerlist=[('Content-Type', 'text/html; charset=UTF-8'),] resp.text=fp.getvalue() resp.content_disposition = 'attachment; filename="qtubes_export.xml"' resp.charset='utf-8' return resp
def _make_response(content, content_type, status, file_name=None): """ Custom response function that is called by pyexcel-webio """ response = Response(content, content_type=content_type, status=status) if file_name: if PY2_VERSION and isinstance(file_name, unicode): file_name = file_name.encode('utf-8') url_encoded_file_name = urllib_quote(file_name) response.content_disposition = ( "attachment; filename=%s;filename*=utf-8''%s" % (url_encoded_file_name, url_encoded_file_name)) return response
def zip(context, request): temp = tempfile.mkdtemp() filename = '%s/%s' % (temp,'buildout.zip') with zipfile.ZipFile(filename, 'w') as buildout: for bfile in context.keys(): buildout.writestr(bfile.encode('utf-8'), context[bfile].data.encode('utf-8')) response = Response() zipped_file = open(filename, 'r') response.body_file = zipped_file response.content_type = 'application/zip' response.content_disposition = "attachment; filename=buildout.zip" return response
def file_download(request): session = request.session if session.get('file_cache'): (filename, mime_type, contents) = session['file_cache'] # Clean the session information regrading the new keypair del session['file_cache'] response = Response(content_type=mime_type) response.body = str(contents) response.content_disposition = 'attachment; filename="{name}"'.format( name=filename) return response # this isn't handled on on client anyway, so we can return pretty much anything return Response(body='BaseView:file not found', status=500)
def __call__(self): check_update = True if self.request.GET.get('check_update', 'true') == 'true' else False package = self.context.__parent__.__parent__ last_remote_version = Package.get_last_remote_version(self.proxy, package.name) if check_update: if not package.repository_is_up_to_date(last_remote_version): return not_found(self.request) response = Response() response.content_disposition = 'attachment; filename="{}"'.format(self.context.filename) response.charset = 'utf-8' response.content_type = self.context.content_type response.body_file = self.context.content.open() return response
def _make_response(content, content_type, status, file_name=None): """ Custom response function that is called by pyexcel-webio """ response = Response(content, content_type=content_type, status=status) if file_name: if PY2_VERSION and isinstance(file_name, unicode): file_name = file_name.encode('utf-8') url_encoded_file_name = urllib_quote(file_name) response.content_disposition = ( "attachment; filename=%s;filename*=utf-8''%s" % (url_encoded_file_name, url_encoded_file_name) ) return response
def api_action_get_bpmn_data(self): """ Generates the BPMN-Data for visulisation :return: Response with the BPMN-xml """ ae = self.pool.get_AppEnsemble(self.uri) bpmn = ae.get_bpm() response = Response( body=bpmn, request=self.request, content_type='txt/xml' ) response.content_disposition = 'attachement; filename="' + str(self.uri) + ".bpmn" return response
def export(request): from pyramid.response import Response from pyramid.httpexceptions import HTTPServerError from subprocess import Popen, PIPE import os.path import datetime response = Response( content_type='application/zip', ) if not os.path.isdir('.git'): raise HTTPServerError('not a git directory') try: proc = Popen( [ 'git', 'describe', '--always', ], stdout=PIPE) rev = proc.stdout.read().strip() proc = Popen( [ 'git', 'archive', '--format=zip', '--prefix=oscad/', '-9', 'HEAD', ], stdout=PIPE) except OSError as e: raise HTTPServerError(e) time = datetime.datetime.now().replace(microsecond=0) filename = 'oscad-{}-git-{}.zip'.format( time.isoformat(), rev ) response.content_disposition = 'attachment; filename="{}"'.format(filename) response.body_file = proc.stdout return response
def doc(self): rev_id = self.request.matchdict['rev_id'] bill = self._get_bill(rev_id) document = bill.get('document') if not document: raise HTTPNotFound() pdf_doc = self.request.fs.get_last_version(filename=document['name']) if not pdf_doc: raise HTTPNotFound() resp = Response() resp.content_disposition = 'filename={filename}'.format(filename=document['name']) resp.content_type = pdf_doc.content_type resp.body_file.write(pdf_doc.read()) return resp
def dump_entries_to_excel(entries): def _format_row(a_row): row = list(a_row) row[0] = (row[0].name,) #client row[1] = (row[1].name,) #project row[2] = (row[2],) #ticketid row[3] = (row[3].email,) #email row[4] = (unicode(row[5]),) #desc date_xf = xlwt.easyxf(num_format_str='DD/MM/YYYY') row[5] = (row[6].strftime('%d/%m/%Y'), date_xf) #date row[6] = (round(row[7], 2),) #time return row[:7] wbk = xlwt.Workbook() sheet = wbk.add_sheet('Hours') heading_xf = xlwt.easyxf('font: bold on; align: wrap on, vert centre, horiz center') headings = ('Client', 'Project', 'Ticket id', 'Employee', 'Description', 'Date', 'Time') headings_width = (x*256 for x in (20, 30, 10, 40, 100, 12, 10)) for colx, value in enumerate(headings): sheet.write(0, colx, value, heading_xf) for i, width in enumerate(headings_width): sheet.col(i).width = width sheet.set_panes_frozen(True) sheet.set_horz_split_pos(1) sheet.set_remove_splits(True) for j, row in enumerate(entries): row = _format_row(row) for i, cell in enumerate(row): sheet.write(j+1, i, *cell) file_path = '/tmp/tmp.xls' wbk.save(file_path) file = open(file_path, 'rb') response = Response( content_type='application/vnd.ms-excel', app_iter = file, ) response.headers['Cache-Control'] = 'no-cache' response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime('%d-%m-%Y--%H-%M-%S') return file, response
def file_download(request): if not(BaseView.is_csrf_valid_static(request)): return JSONResponse(status=400, message="missing CSRF token") session = request.session if session.get('file_cache'): (filename, mime_type, contents) = session['file_cache'] # Clean the session information regrading the new keypair del session['file_cache'] response = Response(content_type=mime_type) response.body = str(contents) response.content_disposition = 'attachment; filename="{name}"'.format(name=filename) response.cache_control = 'no-store' response.pragma = 'no-cache' return response # no file found ... # this isn't handled on on client anyway, so we can return pretty much anything return Response(body='BaseView:file not found', status=500)
def __call__(self): check_update = True if self.request.GET.get( 'check_update', 'true') == 'true' else False package = self.context.__parent__.__parent__ last_remote_version = Package.get_last_remote_version( self.proxy, package.name) if check_update: if not package.repository_is_up_to_date(last_remote_version): return not_found(self.request) response = Response() response.content_disposition = 'attachment; filename="{}"'.format( self.context.filename) response.charset = 'utf-8' response.content_type = self.context.content_type response.body_file = self.context.content.open() response.content_length = self.context.size return response
def get_reporting_monthly_usage_file(self): if not self.is_csrf_valid(): return JSONResponse(status=400, message="missing CSRF token") year = int(self.request.params.get('year')) month = int(self.request.params.get('month')) # use "ViewMontlyUsage" call to fetch usage information ret = self.conn.view_monthly_usage(year, month) filename = 'EucalyptusMonthlyUsage-{0}-{1}-{2}.csv'.format( self.request.session.get('account'), year, month ) response = Response(content_type='text/csv') response.text = ret.get('data') response.content_disposition = 'attachment; filename="{name}"'.format(name=filename) response.cache_control = 'no-store' response.pragma = 'no-cache' return response
def view_download_file(context, request): resource = get_resource(context) s3_conn = get_s3_connection(resource) bucket = s3_conn.get_bucket(request.params.get('bucket')) key_path = request.params.get('key') key = bucket.lookup(key_path) response = Response() fp = get_temporary_file(key.size) if fp: key.get_contents_to_file(fp) fp.seek(0) con_dis = 'attachment; filename={0}'.format(basename(key_path)) response.content_disposition = con_dis response.app_iter = fp else: response.text = u'Download it yourself, ' response.text += u'because of large file size: {0}'.format(key.size) return response
def get_reporting_service_usage_file(self): if not self.is_csrf_valid(): return JSONResponse(status=400, message="missing CSRF token") service = self.request.params.get('service') usage_type = self.request.params.get('usageType') granularity = self.request.params.get('granularity') dates = self.dates_from_params(self.request.params) # use "ViewUsage" call to fetch usage information ret = self.conn.view_usage( service, usage_type, 'all', dates.from_date, dates.to_date, report_granularity=granularity ) filename = 'EucalyptusServiceUsage-{0}-{1}-{2}.csv'.format( self.request.session.get('account'), service, usage_type ) response = Response(content_type='text/csv') response.text = ret.get('data') response.content_disposition = 'attachment; filename="{name}"'.format(name=filename) response.cache_control = 'no-store' response.pragma = 'no-cache' return response
def rdf_void_turtle(self): graph = void_dumper(self.request, self.skos_registry) response = Response(content_type='text/turtle') response.body = graph.serialize(format='turtle') response.content_disposition = 'attachment; filename="void.ttl"' return response
def rdf_export(self): graph = utils.rdf_dumper(self.provider) response = Response(content_type='application/rdf+xml') response.body = graph.serialize(format='xml') response.content_disposition = 'attachment; filename="skos.xml"' return response
def rdf_export_turtle(self): graph = utils.rdf_dumper(self.provider) response = Response(content_type='text/turtle') response.body = graph.serialize(format='turtle') response.content_disposition = 'attachment; filename="skos.ttl"' return response
def export(self, extm, params, req): pdf_pagesz = params.pop('pdf_pagesz', 'a4') pdf_orient = params.pop('pdf_orient', 'portrait') try: pdf_hmargins = float(params.pop('pdf_hmargins', 1.8)) except ValueError: pdf_hmargins = 1.8 try: pdf_vmargins = float(params.pop('pdf_vmargins', 2.0)) except ValueError: pdf_vmargins = 2.0 fields = [] flddef = [] col_widths = [] col_flexes = [] total_width = 0 total_flex = 0 for field in extm.export_view: if isinstance(field, PseudoColumn): fld = field field = fld.name else: fld = extm.get_column(field) fields.append(field) flddef.append(fld) width = fld.column_width flex = fld.column_flex if not width: width = fld.pixels if not width: width = 200 width = width / 200 * inch col_widths.append(width) if flex: col_flexes.append(flex) total_flex += flex else: col_flexes.append(None) total_width += width if pdf_pagesz not in PAGE_SIZES: raise ValueError('Unknown page size specified') if pdf_orient not in ('portrait', 'landscape'): raise ValueError('Unknown page orientation specified') res = Response() loc = get_localizer(req) now = datetime.datetime.now() res.last_modified = now res.content_type = 'application/pdf' res.cache_control.no_cache = True res.cache_control.no_store = True res.cache_control.private = True res.cache_control.must_revalidate = True res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN')) if PY3: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.pdf' % ( urllib.parse.quote(loc.translate(extm.menu_name), ''), now.date().isoformat() ) else: res.content_disposition = \ 'attachment; filename*=UTF-8\'\'%s-%s.pdf' % ( urllib.quote(loc.translate(extm.menu_name).encode(), ''), now.date().isoformat() ) for prop in ('__page', '__start', '__limit'): if prop in params: del params[prop] data = extm.read(params, req)['records'] doc = DefaultDocTemplate( res, request=req, pagesize=pdf_pagesz, orientation=pdf_orient, topMargin=pdf_vmargins * cm, leftMargin=pdf_hmargins * cm, rightMargin=pdf_hmargins * cm, bottomMargin=pdf_vmargins * cm, title=loc.translate(_('{0}, exported at {1}')).format( loc.translate(extm.menu_name), format_datetime(now, locale=req.current_locale) ) ) total_width = doc.width - total_width - 12 if total_flex > 0: width_per_flex = total_width / total_flex else: width_per_flex = 0.0 table_widths = [] for idx, field in enumerate(fields): if col_flexes[idx]: table_widths.append(col_flexes[idx] * width_per_flex) else: table_widths.append(col_widths[idx]) ss = req.pdf_styles if ss is None: raise RuntimeError('PDF subsystem is not configured. See application .INI files.') # TODO: add custom extmodel option to specify rowHeights, as an # optimization measure. Otherwise reportlab takes +Inf time on huge # tables. # Crude hack: rowHeights=([0.5 * inch] * (len(data) + 1) table = LongTable( tuple(storyteller(data, fields, flddef, localizer=loc, model=extm, styles=ss)), colWidths=table_widths, repeatRows=1 ) table.setStyle(TABLE_STYLE_DEFAULT) story = [table] doc.build(story) return res
def file_view(request): """ Show an uploaded file. .../{action}/{identifier} """ TEMP_FOLDER_NAME = 'temp' try: action = request.matchdict['action'] identifier = request.matchdict['identifier'] except KeyError: raise HTTPNotFound() # Check if the action is valid if not (action == 'view' or action == 'download'): raise HTTPNotFound() # Check if the identifier is valid if validate_uuid(identifier) is False: raise HTTPNotFound() # Try to find necessary information of the file (mime-type) db_file_query = DBSession.query(File). \ filter(File.identifier == identifier) try: db_file = db_file_query.one() except NoResultFound: raise HTTPNotFound() except MultipleResultsFound: # This should actually never happen since we are dealing with UUIDs raise HTTPNotFound() # Get file extension extension = get_valid_file_extension(request, db_file.mime) if extension is None: # This should also never happen because files without valid mime type # should not have been uploaded in the first place raise HTTPNotFound() # Put together the filename filename = '%s%s' % (identifier, extension) # Try to find the file on disk upload_path = upload_directory_path(request) folder1, folder2 = get_folders_from_identifier(str(identifier)) filepath = os.path.join(upload_path, folder1, folder2, filename) # Check that the file is on the disk temporaryFile = False if not os.path.exists(filepath): # If the file was not found in its proper directory, try to find it in # the temporary upload directory. This means the Activity was not (yet) # submitted and the file is only visible for logged in users. filepath = os.path.join(upload_path, TEMP_FOLDER_NAME, filename) if not os.path.exists(filepath): # If it is still not found, raise error raise HTTPNotFound() # TODO: Authentication: Handle it properly if 'system.Authenticated' not in effective_principals(request): raise HTTPForbidden() temporaryFile = True # If the file is not in the temporary folder, find its Activity versions by # searching for its A_Value (filename|UID). if temporaryFile is False: a_value = '|%s' % db_file.identifier a_db_query = DBSession.query(Activity). \ join(A_Tag_Group, A_Tag_Group.fk_activity == Activity.id). \ join(A_Tag, A_Tag.fk_tag_group == A_Tag_Group.id). \ join(A_Key, A_Tag.fk_key == A_Key.id). \ join(A_Value, A_Tag.fk_value == A_Value.id). \ filter(A_Key.type.ilike('File')). \ filter(A_Value.value.contains(a_value)) # Files for Activities are always visible if there is an active version # having the file attached. # Files for pending versions of Activities are only visible if the # current user is moderator or edited at least one pending version. showFile = False for a in a_db_query.all(): if a.fk_status == 2: # Active: There is an active version with the file, show it showFile = True break if a.fk_status == 1 and request.user is not None: # Pending: Check if user is moderator or created the version. if 'group:moderators' in effective_principals(request): # Moderator showFile = True break if a.changeset.user == request.user: # Editor of a version showFile = True break if showFile is False: raise HTTPForbidden() # Open the file file = open(filepath, 'rb').read() response = Response(body=file, content_type=str(db_file.mime)) if action == 'download': response.content_disposition = 'attachment; filename=%s' % db_file.name return response