def index_html(self, REQUEST=None, RESPONSE=None): """Make it directly viewable when entering the objects URL """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE filename = self.getFilename() if not filename: filename = self.Title() if filename is not None: if REQUEST.HTTP_USER_AGENT.find('MSIE') != -1: if type(filename) is UnicodeType: filename = filename.encode('gb18030') else: filename = unicode(filename).encode('gb18030') header_value = contentDispositionHeader('attachment', 'gb18030', filename=filename) else: header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-disposition", header_value) if hasattr(self, 'tramline_size'): RESPONSE.setHeader('Content-Type', self.getContentType()) if not RESPONSE.getHeader("tramline_file"): RESPONSE.setHeader("tramline_file", "ok") return '/'.join(self.getPhysicalPath()) else: return field = self.getPrimaryField() data = field.getAccessor(self)(REQUEST=REQUEST, RESPONSE=RESPONSE) if data: return data.index_html(REQUEST, RESPONSE)
def index_html(self, instance, REQUEST=None, RESPONSE=None, disposition='inline'): """ make it directly viewable when entering the objects URL """ if REQUEST is None: REQUEST = instance.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE blob = self.getUnwrapped(instance, raw=True) # TODO: why 'raw'? RESPONSE.setHeader('Last-Modified', rfc1123_date(instance._p_mtime)) RESPONSE.setHeader('Content-Type', self.getContentType(instance)) # The only change is to comment out this header: #RESPONSE.setHeader('Accept-Ranges', 'bytes') if handleIfModifiedSince(instance, REQUEST, RESPONSE): return '' length = blob.get_size() RESPONSE.setHeader('Content-Length', length) filename = self.getFilename(instance) if filename is not None: filename = IUserPreferredFileNameNormalizer(REQUEST).normalize( unicode(filename, instance.getCharset())) header_value = contentDispositionHeader(disposition=disposition, filename=filename) RESPONSE.setHeader("Content-disposition", header_value) range = handleRequestRange(instance, length, REQUEST, RESPONSE) return blob.getIterator(**range)
def generateEmailList(self): """ returns a CSV file of users' emails""" email_list = '' pas = self.context.acl_users users = pas.getUsers() for user in users: roles = '' for portal_role in user.getRoles(): roles += portal_role + ',' roles = '"%s"' %(roles) email_list += unicode(user.getProperty('fullname'),'UTF-8') + ',' + user.getProperty('email') + ',' + user.getUserName() + ',' + roles + '\n' RESPONSE = self.context.REQUEST.RESPONSE filename = 'email_list.csv' header_value = contentDispositionHeader('attachment', 'UTF-8',filename=filename) RESPONSE.setHeader("Content-disposition", header_value) return email_list
def index_html(self, instance, REQUEST=None, RESPONSE=None, disposition='inline'): """ make it directly viewable when entering the objects URL """ if REQUEST is None: REQUEST = instance.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE blob = self.getUnwrapped(instance, raw=True) # TODO: why 'raw'? RESPONSE.setHeader('Last-Modified', rfc1123_date(instance._p_mtime)) RESPONSE.setHeader('Content-Type', self.getContentType(instance)) # The only change is to comment out this header: #RESPONSE.setHeader('Accept-Ranges', 'bytes') if handleIfModifiedSince(instance, REQUEST, RESPONSE): return '' length = blob.get_size() RESPONSE.setHeader('Content-Length', length) filename = self.getFilename(instance) if filename is not None: filename = IUserPreferredFileNameNormalizer(REQUEST).normalize( unicode(filename, instance.getCharset())) header_value = contentDispositionHeader( disposition=disposition, filename=filename) RESPONSE.setHeader("Content-disposition", header_value) range = handleRequestRange(instance, length, REQUEST, RESPONSE) return blob.getIterator(**range)
def download_tsv(self, REQUEST=None, RESPONSE=None): # """Download the saved data # """ filename = self.id if filename.find('.') < 0: filename = '%s.tsv' % filename header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader( "Content-Type", 'text/tab-separated-values;charset=%s' % self.getCharset()) if getattr(self, 'UseColumnNames', False): res = "%s\n" % '\t'.join( self.getColumnNames(excludeServerSide=False)) if isinstance(res, str): res = res.encode(self.getCharset()) else: res = '' for row in self.getSavedFormInput(): res = '%s%s\n' % (res, '\t'.join( [self._cleanInputForTSV(col) for col in row])) return res
def download_csv(self, REQUEST=None, RESPONSE=None): # """Download the saved data # """ filename = self.id if filename.find('.') < 0: filename = '%s.csv' % filename header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader( "Content-Type", 'text/comma-separated-values;charset=%s' % self.getCharset()) if getattr(self, 'UseColumnNames', False): delimiter = self.csvDelimiter() res = "%s\n" % delimiter.join( self.getColumnNames(excludeServerSide=False)) if isinstance(res, str): res = res.encode(self.getCharset()) else: res = '' return '%s%s' % (res, self.getSavedFormInputForEdit())
def index_html(self, REQUEST=None, RESPONSE=None, charset='utf-8', disposition='inline'): """ make it directly viewable when entering the objects URL """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) RESPONSE.setHeader('Content-Type', self.getContentType()) RESPONSE.setHeader('Accept-Ranges', 'bytes') if handleIfModifiedSince(self, REQUEST, RESPONSE): return '' length = self.get_size() RESPONSE.setHeader('Content-Length', length) filename = self.getFilename() if filename is not None: if not isinstance(filename, unicode): filename = unicode(filename, charset) filename = IUserPreferredFileNameNormalizer(REQUEST).normalize( filename) header_value = contentDispositionHeader( disposition=disposition, filename=filename) RESPONSE.setHeader("Content-disposition", header_value) request_range = handleRequestRange(self, length, REQUEST, RESPONSE) return self.getIterator(**request_range)
def __call__(self, name, rev=False): field = self.context.getField(name) if not rev: return field.download(self.context) storage = field.getStorage(self.context) info = storage.getInfoByRevision(self.context, name, rev) if not info: return field.download(self.context) contents = storage.getByRevision(self.context, name, rev) filename = field.getFilename(self.context) if not filename: filename = os.path.basename(info["filepath"]) kwargs = {"filename": filename, "mimetype": info["mimetype"]} file = field._wrapValue(self.context, contents, **kwargs) if filename is not None: if FILE_NORMALIZER: filename = IUserPreferredFileNameNormalizer(self.request).normalize( unicode(filename, self.context.getCharset()) ) else: filename = unicode(filename, self.context.getCharset()) header_value = contentDispositionHeader(disposition="attachment", filename=filename) self.request.RESPONSE.setHeader("Content-Disposition", header_value) return file.index_html(self.request, self.request.RESPONSE)
def __call__(self): context = aq_inner(self.context) request = self.request response_id = self.validate_response_id() file = None if response_id != -1: response = self.folder[response_id] file = response.attachment if file is None: status = IStatusMessage(request) msg = _(u"Response id ${response_id} has no attachment.", mapping=dict(response_id=response_id)) msg = translate(msg, 'Poi', context=context) status.addStatusMessage(msg, type='error') if file is None: request.response.redirect(context.absolute_url()) # From now on file exists. # Code mostly taken from Archetypes/Field.py:FileField.download filename = getattr(file, 'filename', file.getId()) if filename is not None: if FILE_NORMALIZER: filename = IUserPreferredFileNameNormalizer(request).normalize( safe_unicode(filename, context.getCharset())) else: filename = safe_unicode(filename, context.getCharset()) header_value = contentDispositionHeader( disposition='attachment', filename=filename) request.response.setHeader("Content-disposition", header_value) return file.index_html(request, request.response)
def index_html(self, REQUEST=None, RESPONSE=None, charset='utf-8', disposition='inline'): """ make it directly viewable when entering the objects URL """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) RESPONSE.setHeader('Content-Type', self.getContentType()) RESPONSE.setHeader('Accept-Ranges', 'bytes') if handleIfModifiedSince(self, REQUEST, RESPONSE): return '' length = self.get_size() RESPONSE.setHeader('Content-Length', length) filename = self.getFilename() if filename is not None: if REQUEST.HTTP_USER_AGENT.find('MSIE') != -1: if isinstance(filename, unicode): filename = filename.encode('gb18030') else: filename = unicode(filename, charset, errors="ignore") filename = filename.encode('gb18030') header_value = contentDispositionHeader(disposition, 'gb18030', filename=filename) else: if not isinstance(filename, unicode): filename = unicode(filename, charset, errors="ignore") # filename = IUserPreferredFileNameNormalizer(REQUEST).normalize( # filename) header_value = contentDispositionHeader(disposition=disposition, filename=filename) RESPONSE.setHeader("Content-disposition", header_value) request_range = handleRequestRange(self, length, REQUEST, RESPONSE) return self.getIterator(**request_range)
def exportToCSV(self): currentDateTime = time.strftime('%Y%m%d%H%M', time.localtime()) filename = '%s-%s.csv' % (self.context.Title(), currentDateTime) header_value = contentDispositionHeader('attachment', self.context.getCharset(), filename=filename) self.request.response.setHeader('Content-Disposition', header_value) self.request.response.setHeader('Content-Type', 'text/comma-separated-values;charset=%s' % self.context.getCharset()) return self.context.exportToCSV()
def download(self, instance, REQUEST=None, RESPONSE=None): """Kicks download. Writes data including file name and content type to RESPONSE """ file = self.get(instance) if not REQUEST: REQUEST = instance.REQUEST if not RESPONSE: RESPONSE = REQUEST.RESPONSE filename = self.getFilename(instance) if not filename: filename = instance.Title() if filename is not None: if REQUEST.HTTP_USER_AGENT.find('MSIE') != -1: if type(filename) is UnicodeType: filename = filename.encode('gb18030') else: filename = unicode(filename).encode('gb18030') header_value = contentDispositionHeader('attachment', 'gb18030', filename=filename) else: header_value = contentDispositionHeader('attachment', instance.getCharset(), filename=filename) RESPONSE.setHeader("Content-disposition", header_value) if hasattr(instance.aq_base, 'tramline_size'): archiveName = REQUEST.get('archive_name', '') zpath = '/'.join(instance.getPhysicalPath()) if archiveName: # 下载ä¸é—´çš„å˜æ¡£ç‰ˆæœ¬ RESPONSE.setHeader('Content-Type', self.getContentType(instance)) RESPONSE.setHeader("tramline_file", "ok") return zpath + ':archive::' + archiveName else: RESPONSE.setHeader('Content-Type', self.getContentType(instance)) RESPONSE.setHeader("tramline_file", "ok") return zpath return file.index_html(REQUEST, RESPONSE)
def index_html(self, REQUEST=None, RESPONSE=None): """Make it directly viewable when entering the objects URL """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE filename = self.getFilename() if not filename: filename = self.Title() if filename is not None: if REQUEST.HTTP_USER_AGENT.find('MSIE') != -1: if type(filename) is UnicodeType: filename = filename.encode('gb18030') else: filename = unicode(filename).encode('gb18030') header_value = contentDispositionHeader('attachment', 'gb18030', filename=filename) else: header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-disposition", header_value) if hasattr(self, 'tramline_size'): RESPONSE.setHeader('Content-Type', self.getContentType()) if not RESPONSE.getHeader("tramline_file"): RESPONSE.setHeader("tramline_file", "ok") return '/'.join(self.getPhysicalPath()) else: return field = self.getPrimaryField() data = field.getAccessor(self)(REQUEST=REQUEST, RESPONSE=RESPONSE) if data: return data.index_html(REQUEST, RESPONSE)
def exportToCSV(self): currentDateTime = time.strftime('%Y%m%d%H%M', time.localtime()) filename = '%s-%s.csv' % (self.context.Title(), currentDateTime) header_value = contentDispositionHeader('attachment', self.context.getCharset(), filename=filename) self.request.response.setHeader('Content-Disposition', header_value) self.request.response.setHeader( 'Content-Type', 'text/comma-separated-values;charset=%s' % self.context.getCharset()) return self.context.exportToCSV()
def download(self, instance, REQUEST=None, RESPONSE=None): """Kicks download. Writes data including file name and content type to RESPONSE """ file = self.get(instance) if not REQUEST: REQUEST = instance.REQUEST if not RESPONSE: RESPONSE = REQUEST.RESPONSE filename = self.getFilename(instance) if not filename: filename = instance.Title() if filename is not None: if REQUEST.HTTP_USER_AGENT.find('MSIE') != -1: if type(filename) is UnicodeType: filename = filename.encode('gb18030') else: filename = unicode(filename).encode('gb18030') header_value = contentDispositionHeader('attachment', 'gb18030', filename=filename) else: header_value = contentDispositionHeader('attachment', instance.getCharset(), filename=filename) RESPONSE.setHeader("Content-disposition", header_value) if hasattr(instance.aq_base, 'tramline_size'): archiveName = REQUEST.get('archive_name', '') zpath = '/'.join(instance.getPhysicalPath()) if archiveName: # 下载ä¸é—´çš„å˜æ¡£ç‰ˆæœ¬ RESPONSE.setHeader('Content-Type', self.getContentType(instance)) RESPONSE.setHeader("tramline_file", "ok") return zpath + ':archive::' + archiveName else: RESPONSE.setHeader('Content-Type', self.getContentType(instance)) RESPONSE.setHeader("tramline_file", "ok") return zpath return file.index_html(REQUEST, RESPONSE)
def download_xlsx(self, REQUEST=None, RESPONSE=None, plain=False): if not plain: filename = '%s.xlsx' % self.id header_value = contentDispositionHeader('attachment', 'l1', filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader("Content-Type", 'application/vnd.ms-excel') display_header = getattr(self, 'UseColumnNames', False) values = self.getSavedFormInput() if display_header: return self.create_export_excel(values, self.getShowColumnTitles()) return self.create_export_excel(values)
def __call__(self): """ This is the image - if possible without the legend """ request = self.request alsoProvides(request, IDisableCSRFProtection) refresh = request.get("refresh", False) response = request.RESPONSE response.setHeader('Content-Type', 'image/png') response.setHeader('Cache-control', 'max-age=300,s-maxage=300,must-revalidate') # Get doc image but without legend data, filename = self.context.getMyImage(refresh=refresh, full=False) header_value= contentDispositionHeader('inline', filename=filename, charset='latin-1') response.setHeader('Content-disposition', header_value) response.setHeader('Content-Length', len(data)) return data
def download_xls(self, REQUEST=None, RESPONSE=None): # """Download the saved data # """ filename = self.id if filename.find('.') < 0: filename = '%s.xls' % filename header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader("Content-Type", 'application/vnd.ms-excel') xldoc = xlwt.Workbook(encoding=self.getCharset()) sheet = xldoc.add_sheet(self.Title()) row_num = 0 if getattr(self, 'UseColumnNames', False): col_names = self.getColumnNames(excludeServerSide=False) for idx, label in enumerate(col_names): sheet.write(0, idx, label.encode(self.getCharset())) row_num += 1 for row in self.getSavedFormInput(): for col_num, col in enumerate(row): if type(col) is str: col = col.encode(self.getCharset()) if urlparse(col).scheme in ('http', 'https'): col = xlwt.Formula('HYPERLINK("%(url)s")' % dict(url=col)) else: for format in (int, float): try: col = format(col) break except ValueError: pass sheet.write(row_num, col_num, col) row_num += 1 string_buffer = StringIO() xldoc.save(string_buffer) return string_buffer.getvalue()
def download_csv(self, REQUEST=None, RESPONSE=None): """Download the saved data """ filename = self.id if filename.find('.') < 0: filename = '%s.csv' % filename header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader("Content-Type", 'text/comma-separated-values;charset=%s' % self.getCharset()) if getattr(self, 'UseColumnNames', False): res = "%s\n" % ','.join( self.getColumnNames() ) if isinstance(res, unicode): res = res.encode(self.getCharset()) else: res = '' return '%s%s' % (res, self.getSavedFormInputForEdit())
def download(self, REQUEST=None, RESPONSE=None): """Download the saved data """ url_tool = getToolByName(self, 'portal_url') config = IConfig(url_tool.getPortalObject()) pub_state = getMultiAdapter((self, REQUEST), IPublisherContextState) realms = config.getRealms() download_format = getattr(self, 'DownloadFormat', 'csv') if len(realms) == 0 or not pub_state.is_parent_published(): if download_format == 'tsv': return self.download_tsv(REQUEST, RESPONSE) else: assert download_format == 'csv', 'Unknown download format' return self.download_csv(REQUEST, RESPONSE) elif len(realms) == 1: data = {'uid': self.UID(), 'download_format': download_format} return_data_realm = sendRequestToRealm(data, realms[0], 'formgen_get_saved_data') return_data_this = self.getSavedFormInputForEdit() return_data = '{}{}'.format(return_data_realm, return_data_this) filename = self.id if filename.find('.') < 0: filename = '%s.%s' % (filename, download_format) header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) sep_type = download_format == 'csv' and 'comma' or 'tab' RESPONSE.setHeader("Content-Type", 'text/%s-separated-values;' 'charset=%s' % (sep_type, self.getCharset())) return return_data else: messages = IStatusMessage(self.request) messages.add(_(u"couldn't determine correct realm to fetch from."), type=u"error") return RESPONSE.redirect(self.context.absolute_url())
def download_xls(self, REQUEST=None, RESPONSE=None): # """Download the saved data # """ filename = self.id if filename.find('.') < 0: filename = '%s.xls' % filename header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader("Content-Type", 'application/vnd.ms-excel') xldoc = xlwt.Workbook(encoding=self.getCharset()) sheet = xldoc.add_sheet(self.Title()) row_num = 0 if getattr(self, 'UseColumnNames', False): col_names = self.getColumnNames(excludeServerSide=False) for idx, label in enumerate(col_names): sheet.write(0, idx, label.encode(self.getCharset())) row_num += 1 for row in self.getSavedFormInput(): for col_num, col in enumerate(row): if type(col) is unicode: col = col.encode(self.getCharset()) if urlparse(col).scheme in ('http', 'https'): col = xlwt.Formula('HYPERLINK("%(url)s")' % dict(url=col)) else: for format in (int, float): try: col = format(col) break except ValueError: pass sheet.write(row_num, col_num, col) row_num += 1 string_buffer = StringIO() xldoc.save(string_buffer) return string_buffer.getvalue()
def _attach_to_response(self, request, data, extension, filename=None): if not filename: filename = self.context.id if isinstance(filename, unicode): filename = filename.encode('utf-8') filename = '{}.{}'.format(filename, extension) response = request.RESPONSE response.setHeader('Content-Type', 'application/%s; charset=utf-8' % extension) response.setHeader( 'Content-disposition', contentDispositionHeader( 'attachment', 'utf-8', filename=filename)) response.write(data) return request
def render_blob_version(self): # done much like it is done in plone.app.blob's index_html header_value = contentDispositionHeader( disposition='inline', filename=self.context.getFilename().replace('.pdf', '.swf')) blob = self.settings.data blobfi = openBlob(blob) length = fstat(blobfi.fileno()).st_size blobfi.close() self.request.response.setHeader('Last-Modified', rfc1123_date(self.context._p_mtime)) self.request.response.setHeader('Accept-Ranges', 'bytes') self.request.response.setHeader('Content-Disposition', header_value) self.request.response.setHeader("Content-Length", length) self.request.response.setHeader('Content-Type', 'application/x-shockwave-flash') range = handleRequestRange(self.context, length, self.request, self.request.response) return BlobStreamIterator(blob, **range)
def render_blob_version(self): # done much like it is done in plone.app.blob's index_html header_value = contentDispositionHeader( disposition='inline', filename=self.context.getFilename().replace('.pdf', '.swf')) blob = self.settings.data blobfi = openBlob(blob) length = fstat(blobfi.fileno()).st_size blobfi.close() self.request.response.setHeader('Last-Modified', rfc1123_date(self.context._p_mtime)) self.request.response.setHeader('Accept-Ranges', 'bytes') self.request.response.setHeader('Content-Disposition', header_value) self.request.response.setHeader("Content-Length", length) self.request.response.setHeader('Content-Type', 'application/x-shockwave-flash') range = handleRequestRange(self.context, length, self.request, self.request.response) return BlobStreamIterator(blob, **range)
def __call__(self): if self.request.get("download", None) is None: request.RESPONSE.redirect(self.context.absolute_url()) m = email.message_from_string(self.context.data) parts = [item for item in m.walk() if item.get_filename() != None] if parts[int(self.request.get("download"))].is_multipart(): data = str(parts[int(self.request.get("download"))]) else: data = parts[int(self.request.get("download"))].get_payload(decode=1) REQUEST = self.request RESPONSE = REQUEST.RESPONSE filename = REQUEST.get("filename") mimetype = REQUEST.get("mimetype") if filename is not None: header_value = contentDispositionHeader( disposition='attachment', filename=filename) RESPONSE.setHeader("Content-disposition", header_value) RESPONSE.setHeader("Content-Type", mimetype) return data
def download_tsv(self, REQUEST=None, RESPONSE=None): # """Download the saved data # """ filename = self.id if filename.find('.') < 0: filename = '%s.tsv' % filename header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader("Content-Type", 'text/tab-separated-values;charset=%s' % self.getCharset()) if getattr(self, 'UseColumnNames', False): res = "%s\n" % '\t'.join(self.getColumnNames(excludeServerSide=False)) if isinstance(res, unicode): res = res.encode(self.getCharset()) else: res = '' for row in self.getSavedFormInput(): res = '%s%s\n' % (res, '\t'.join([self._cleanInputForTSV(col) for col in row])) return res
def download(self, REQUEST=None, RESPONSE=None): """Download the saved data """ url_tool = getToolByName(self, 'portal_url') config = IConfig(url_tool.getPortalObject()) pub_state = getMultiAdapter((self, REQUEST), IPublisherContextState) realms = config.getRealms() download_format = getattr(self, 'DownloadFormat', 'csv') if len(realms) == 0 or not pub_state.is_parent_published(): if download_format == 'tsv': return self.download_tsv(REQUEST, RESPONSE) else: assert download_format == 'csv', 'Unknown download format' return self.download_csv(REQUEST, RESPONSE) elif len(realms) == 1: data = {'uid': self.UID(), 'download_format': download_format} return_data = sendRequestToRealm(data, realms[0], 'formgen_get_saved_data') filename = self.id if filename.find('.') < 0: filename = '%s.%s' % (filename, download_format) header_value = contentDispositionHeader('attachment', self.getCharset(), filename=filename) RESPONSE.setHeader("Content-Disposition", header_value) sep_type = download_format == 'csv' and 'comma' or 'tab' RESPONSE.setHeader("Content-Type", 'text/%s-separated-values;' 'charset=%s' % (sep_type, self.getCharset())) return return_data else: messages = IStatusMessage(self.request) messages.add(_(u"couldn't determine correct realm to fetch from."), type=u"error") return RESPONSE.redirect(self.context.absolute_url())
def index_html(self, REQUEST=None, RESPONSE=None, charset='utf-8', disposition='inline'): """ make it directly viewable when entering the objects URL """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE RESPONSE.setHeader('Last-Modified', rfc1123_date(self._p_mtime)) RESPONSE.setHeader('Content-Type', self.getContentType()) RESPONSE.setHeader('Accept-Ranges', 'bytes') if handleIfModifiedSince(self, REQUEST, RESPONSE): return '' length = self.get_size() RESPONSE.setHeader('Content-Length', length) filename = self.getFilename() if filename is not None: if not isinstance(filename, six.text_type): filename = six.text_type(filename, charset, errors='ignore') filename = IUserPreferredFileNameNormalizer( REQUEST, ).normalize( filename, ) header_value = contentDispositionHeader( disposition=disposition, filename=filename, ) # Add original filename in utf-8, ref to rfc2231 RESPONSE.setHeader('Content-disposition', header_value) request_range = handleRequestRange(self, length, REQUEST, RESPONSE) return self.getIterator(**request_range)
def ImageScale_index_html(self, REQUEST=None, RESPONSE=None): """ Inject X-Sendfile and X-Accel-Redirect headers into response. """ if REQUEST is None: REQUEST = self.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE blob = getattr(self, "blob", None) if not blob: return super(ImageScale, self).index_html(REQUEST, RESPONSE) if set_xsendfile_header(REQUEST, RESPONSE, blob): filename = self.filename if self.filename is not None: normalizer = IUserPreferredFileNameNormalizer(REQUEST) filename = normalizer.normalize(unicode(self.filename, self.getCharset())) header_value = contentDispositionHeader(disposition="inline", filename=filename) RESPONSE.setHeader("Content-disposition", header_value) RESPONSE.setHeader("Content-Type", self.content_type) return "collective.xsendfile - proxy missing?" else: return super(ImageScale, self).index_html(REQUEST, RESPONSE)
def index_html(self, instance, REQUEST=None, RESPONSE=None, disposition='inline', **kwargs): """ Field public view """ storage = self.getStorage() zfile = storage.get('file', instance) if not isinstance(zfile, ZFile): return super(FlashFileField, self).index_html(instance, REQUEST, RESPONSE, disposition, **kwargs) # BBB Backward compatible: OFS.Image.File if not REQUEST: REQUEST = instance.REQUEST if not RESPONSE: RESPONSE = REQUEST.RESPONSE filename = getattr(zfile, 'filename', instance.getId()) header_value = contentDispositionHeader(disposition='attachment', filename=filename) RESPONSE.setHeader("Content-disposition", header_value) return zfile.index_html(REQUEST, RESPONSE)
tmpfile.writelines(table_columns) tmpfile.close() file = open(tmpfilename, "rb") csvdata = file.read() groesse = len(csvdata) file.close() try: os.remove(tmpfilename) except Exception, e: log_exc(e) if REQUEST is not None and not justData: RESPONSE = REQUEST.RESPONSE header_value = contentDispositionHeader('attachment', filename='%s_%s.csv' % (typ, DateTime().millis()), charset='latin-1') RESPONSE.setHeader("Content-disposition", header_value) RESPONSE.setHeader("Content-Type", 'text/csv') if groesse: RESPONSE.setHeader("Content-Length", groesse) log('EXPORTFILTER: %s' % filter) log('EXPORTSORT_ON: %s' % sort_on) log('EXPORTSORT_ORDER: %s' % sort_order) log('%s von %s Objekten des Typs %s exportiert' % (len(objekte) - errors, len(objekte), typ)) else: log('Dieser Typ: %s ist nicht exportfaehig, da keine to_dict-Methode implementiert ist.' % typ) return csvdata def reportObjekte(self, reportcontext, typ, sort_on, sort_order, filter={}, reportname='Standard', test=False, **templatevars): """
def download_csv(self): """Returns a CSV file containing the shop orders """ filename = "orders.csv" stream = cStringIO.StringIO() csv_writer = csv.writer(stream, dialect='excel', delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL) core_cols = ['order_id', 'title', 'status', 'total', 'date', 'customer_title', 'customer_firstname', 'customer_lastname', 'customer_company', 'customer_email', 'customer_street1', 'customer_street2', 'customer_phone', 'customer_zipcode', 'customer_city', 'customer_shipping_address', 'customer_country', 'customer_comments'] # Create union of core_cols + all_cols to retain order all_cols = self.order_storage.getFieldNames() columns = core_cols + filter(lambda x:x not in core_cols, all_cols) cart_cols = ['sku_code', 'quantity', 'dimensions', 'title', 'price', 'item_total', 'supplier_name', 'supplier_email'] column_titles = [COLUMN_TITLES[col].decode('utf-8').encode('cp1252') for col in columns + cart_cols] # Write header row csv_writer.writerow(column_titles) for order in self.order_results: order_data = [getattr(order, attr, '') for attr in columns] # Get the total via getTotal accessor to convert it to Decimal order_data[columns.index('total')] = order.getTotal() for i, value in enumerate(order_data): if isinstance(value, unicode): order_data[i] = value.encode('cp1252') for cart_item in order.cartitems: # format dimensions dimensions = [(cart_item.dimensions[i], dim) for i, dim in enumerate(cart_item.selectable_dimensions)] dim_strings = [' '.join([str(dim[0]), translate(_(dim[1]), context=self.request)]) for dim in dimensions] dim_formatted = ','.join(dim_strings) cart_data = [cart_item.sku_code, cart_item.quantity, dim_formatted, cart_item.title, cart_item.getPrice(), cart_item.getTotal(), cart_item.supplier_name, cart_item.supplier_email] for i, value in enumerate(cart_data): if isinstance(value, unicode): cart_data[i] = value.encode('cp1252') csv_writer.writerow(order_data + cart_data) RESPONSE = self.request.RESPONSE header_value = contentDispositionHeader('attachment', 'cp1252', filename=filename) if not DEBUG: RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader("Content-Type", 'text/comma-separated-values;charset=%s' % 'cp1252') else: RESPONSE.setHeader("Content-Type", 'text/plain; charset=%s' % 'cp1252') stream.seek(0) return stream.read()
def index_html(self, instance=None, REQUEST=None, RESPONSE=None, disposition='inline'): """ Inject X-Sendfile and X-Accel-Redirect headers into response. """ try: registry = getUtility(IRegistry) settings = registry.forInterface(IxsendfileSettings) except ComponentLookupError: # This happens when collective.xsendfile egg is in place # but add-on installer has not been run yet settings = None logger.warn("Could not load collective.xsendfile settings") if REQUEST is None: REQUEST = instance.REQUEST if RESPONSE is None: RESPONSE = REQUEST.RESPONSE filename = self.getFilename(instance) if filename is not None: filename = IUserPreferredFileNameNormalizer(REQUEST).normalize( unicode(filename, instance.getCharset())) header_value = contentDispositionHeader( disposition=disposition, filename=filename) RESPONSE.setHeader("Content-disposition", header_value) blob = self.getUnwrapped(instance, raw=True) # TODO: why 'raw'? zodb_blob = blob.getBlob() blob_file = zodb_blob.open() file_path = blob_file.name blob_file.close() RESPONSE.setHeader('Last-Modified', rfc1123_date(instance._p_mtime)) RESPONSE.setHeader("Content-Length", blob.get_size()) RESPONSE.setHeader('Content-Type', self.getContentType(instance)) if settings is not None: responseheader = settings.xsendfile_responseheader pathregex_search = settings.xsendfile_pathregex_search pathregex_substitute = settings.xsendfile_pathregex_substitute enable_fallback = settings.xsendfile_enable_fallback if responseheader and pathregex_substitute: file_path = re.sub(pathregex_search,pathregex_substitute,file_path) fallback = False if not responseheader: fallback = True logger.warn("No front end web server type selected") if enable_fallback: if (not REQUEST.get('HTTP_X_FORWARDED_FOR')): fallback = True else: # Not yet installed through add-on installer fallback = True if fallback: logger.warn("Falling back to sending object %s.%s via Zope"%(repr(instance),repr(self), )) return zodb_blob.open().read() else: logger.debug("Sending object %s.%s with xsendfile header %s, path: %s"%(repr(instance), repr(self), repr(responseheader), repr(file_path))) RESPONSE.setHeader(responseheader, file_path) return "collective.xsendfile - proxy missing?"
def download_csv(self): """Returns a CSV file containing the shop orders """ filename = "orders.csv" stream = cStringIO.StringIO() csv_writer = csv.writer(stream, dialect='excel', delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL) core_cols = ['order_id', 'title', 'status', 'total', 'date', 'customer_title', 'customer_firstname', 'customer_lastname', 'customer_company', 'customer_email', 'customer_street1', 'customer_street2', 'customer_phone', 'customer_zipcode', 'customer_city', 'customer_shipping_address', 'customer_country', 'customer_comments'] # Create union of core_cols + all_cols to retain order all_cols = self.order_storage.getFieldNames() columns = core_cols + filter(lambda x:x not in core_cols, all_cols) cart_cols = ['sku_code', 'quantity', 'title', 'price', 'item_total', 'supplier_name', 'supplier_email'] column_titles = [COLUMN_TITLES[col].decode('utf-8').encode('cp1252') for col in columns + cart_cols] # Write header row csv_writer.writerow(column_titles) for order in self.order_results: order_data = [getattr(order, attr, '') for attr in columns] # Get the total via getTotal accessor to convert it to Decimal order_data[columns.index('total')] = order.getTotal() for i, value in enumerate(order_data): if isinstance(value, unicode): order_data[i] = value.encode('cp1252') for cart_item in order.cartitems: cart_data = [cart_item.sku_code, cart_item.quantity, cart_item.title, cart_item.getPrice(), cart_item.getTotal(), cart_item.supplier_name, cart_item.supplier_email] for i, value in enumerate(cart_data): if isinstance(value, unicode): cart_data[i] = value.encode('cp1252') csv_writer.writerow(order_data + cart_data) RESPONSE = self.request.RESPONSE header_value = contentDispositionHeader('attachment', 'cp1252', filename=filename) if not DEBUG: RESPONSE.setHeader("Content-Disposition", header_value) RESPONSE.setHeader("Content-Type", 'text/comma-separated-values;charset=%s' % 'cp1252') else: RESPONSE.setHeader("Content-Type", 'text/plain; charset=%s' % 'cp1252') stream.seek(0) return stream.read()