本文整理汇总了Python中wsgiref.util.FileWrapper方法的典型用法代码示例。如果您正苦于以下问题:Python util.FileWrapper方法的具体用法?Python util.FileWrapper怎么用?Python util.FileWrapper使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wsgiref.util
的用法示例。
在下文中一共展示了util.FileWrapper方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_activity_zip
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def generate_activity_zip(self):
"""
Create ZIP file for this activity
"""
handle, filename = tempfile.mkstemp('.zip')
os.close(handle)
z = zipfile.ZipFile(filename, 'w')
self.generate_submission_contents(z, prefix='')
z.close()
file = open(filename, 'rb')
response = StreamingHttpResponse(FileWrapper(file), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s.zip"' % (self.activity.slug)
try:
os.remove(filename)
except OSError:
pass
return response
示例2: checkFW
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def checkFW(self,text,size,match):
def make_it(text=text,size=size):
return util.FileWrapper(StringIO(text),size)
compare_generic_iter(make_it,match)
it = make_it()
self.assertFalse(it.filelike.closed)
for item in it:
pass
self.assertFalse(it.filelike.closed)
it.close()
self.assertTrue(it.filelike.closed)
示例3: download
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def download(self,path,file_or_dir):
if not re.match(r'[\w\d_ -/]*',path).group(0) == path:
return HttpResponse('Invalid path')
if file_or_dir == 'file':
filepath = self.basepath + '/' + path
wrapper = FileWrapper(file(filepath))
response = HttpResponse(wrapper, content_type=mimetypes.guess_type(filepath)[0])
response['Content-Length'] = os.path.getsize(filepath)
response['Content-Disposition'] = 'attachment; filename='+path.split('/')[-1]
return response
elif file_or_dir == 'dir':
dirpath = self.basepath + '/' + path
dirname = dirpath.split('/')[-2]
response = HttpResponse(content_type='application/x-gzip')
response['Content-Disposition'] = 'attachment; filename=%s.tar.gz' % dirname
tarred = tarfile.open(fileobj=response, mode='w:gz')
tarred.add(dirpath,arcname=dirname)
tarred.close()
return response
示例4: DownloadFile
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def DownloadFile(data, filename, content_type='application/text'):
""" Create a dynamic file for the user to download.
Args:
data: Raw file data (string or bytes)
filename: Filename for the file download
content_type: Content type for the download
Return:
A StreamingHttpResponse object wrapping the supplied data
"""
filename = WrapWithQuotes(filename)
if type(data) == str:
wrapper = FileWrapper(io.StringIO(data))
else:
wrapper = FileWrapper(io.BytesIO(data))
response = StreamingHttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = len(data)
response['Content-Disposition'] = 'attachment; filename={f}'.format(f=filename)
return response
示例5: serve_pdf_galley_to_browser
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def serve_pdf_galley_to_browser(request, file, article):
"""
Serves a file to the browser so that it displays in the browser.
:param request: HttpRequest object
:param file: File object
:param article: Article object
:return: HttpResponse
"""
file_path = os.path.join(
settings.BASE_DIR,
'files',
'articles',
str(article.id),
str(file.uuid_filename)
)
try:
response = HttpResponse(
FileWrapper(open(file_path, 'rb')),
content_type=file.mime_type
)
return response
except IOError:
messages.add_message(request, messages.ERROR, 'File not found.')
raise Http404
示例6: download
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def download(request):
"""Download from MobSF Route."""
msg = 'Error Downloading File '
if request.method == 'GET':
allowed_exts = settings.ALLOWED_EXTENSIONS
filename = request.path.replace('/download/', '', 1)
# Security Checks
if '../' in filename:
msg = 'Path Traversal Attack Detected'
return print_n_send_error_response(request, msg)
ext = os.path.splitext(filename)[1]
if ext in allowed_exts:
dwd_file = os.path.join(settings.DWD_DIR, filename)
if os.path.isfile(dwd_file):
wrapper = FileWrapper(open(dwd_file, 'rb'))
response = HttpResponse(
wrapper, content_type=allowed_exts[ext])
response['Content-Length'] = os.path.getsize(dwd_file)
return response
if ('screen/screen.png' not in filename
and '-icon.png' not in filename):
msg += filename
return print_n_send_error_response(request, msg)
return HttpResponse('')
示例7: checkFW
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def checkFW(self,text,size,match):
def make_it(text=text,size=size):
return util.FileWrapper(StringIO(text),size)
compare_generic_iter(make_it,match)
it = make_it()
self.failIf(it.filelike.closed)
for item in it:
pass
self.failIf(it.filelike.closed)
it.close()
self.failUnless(it.filelike.closed)
示例8: get
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def get(self, request, *args, **kwargs):
post = get_object_or_404(self.get_queryset(), pk=self.kwargs['pk'])
if request.user.is_superuser or request.user.has_perm('archives.change_post') or post.author_id == request.user.id:
pass
elif post.visible == 'private' or post.visible == 'sell' and not post.buyers.filter(id=request.user.id).exists():
raise Http404
chunk_size = 8192
response = StreamingHttpResponse(FileWrapper(open(post.attachment.path, 'rb'), chunk_size),
content_type='application/octet-stream')
response['Content-Length'] = post.attachment.size
filename = post.attachment_filename if post.attachment_filename else 'attachment'
response["Content-Disposition"] = \
"attachment; " \
"filenane={ascii_filename};" \
"filename*=UTF-8''{utf_filename}".format(
ascii_filename=quote(filename),
utf_filename=quote(filename)
)
return response
示例9: streamRanges
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def streamRanges(request, path, content_type=None):
range_header = request.META.get('HTTP_RANGE', '').strip()
range_match = range_re.match(range_header)
size = os.path.getsize(path)
if not content_type:
content_type, encoding = mimetypes.guess_type(path)
content_type = content_type or 'application/octet-stream'
if range_match:
first_byte, last_byte = range_match.groups()
first_byte = int(first_byte) if first_byte else 0
last_byte = int(last_byte) if last_byte else size - 1
if last_byte >= size:
last_byte = size - 1
length = last_byte - first_byte + 1
resp = StreamingHttpResponse(RangeFileWrapper(open(path, 'rb'), offset=first_byte, length=length), status=206, content_type=content_type)
resp['Content-Length'] = str(length)
resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, size)
else:
resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
resp['Content-Length'] = str(size)
resp['Accept-Ranges'] = 'bytes'
return resp
示例10: app
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def app(environ, respond):
fn = os.path.join(path, environ['PATH_INFO'][1:])
if '.' not in fn.split(os.path.sep)[-1]:
fn = os.path.join(fn, 'index.html')
type = mimetypes.guess_type(fn)[0]
if os.path.exists(fn):
respond('200 OK', [('Content-Type', type)])
return util.FileWrapper(open(fn, "rb"))
else:
respond('404 Not Found', [('Content-Type', 'text/plain')])
return [b'not found']
示例11: get_wrapper
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def get_wrapper(self):
from wsgiref.util import FileWrapper
return FileWrapper(file(self.path))
示例12: generate_student_zip
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def generate_student_zip(self):
self.ensure_components()
assert self.submissions
multi = self.activity.multisubmit()
if multi:
self.get_all_components()
compsub = self.all_components_and_submitted()
else:
self.get_most_recent_components()
compsub = self.components_and_submitted()
handle, filename = tempfile.mkstemp('.zip')
os.close(handle)
z = zipfile.ZipFile(filename, 'w')
self._add_to_zip(z, self.activity, compsub, self.submissions[0].created_at,
slug=self.submissions[0].file_slug(), multi=multi)
z.close()
file = open(filename, 'rb')
response = StreamingHttpResponse(FileWrapper(file), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s_%s.zip"' % (
self.submissions[0].file_slug(), self.activity.slug)
try:
os.remove(filename)
except OSError:
pass
return response
示例13: download_spss_labels
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def download_spss_labels(request, username, form_id_string):
xform = get_object_or_404(XForm,
user__username__iexact=username,
id_string__exact=form_id_string)
owner = User.objects.get(username__iexact=username)
helper_auth_helper(request)
if not has_permission(xform, owner, request, xform.shared):
return HttpResponseForbidden('Not shared.')
try:
xlsform_io= xform.to_xlsform()
if not xlsform_io:
messages.add_message(request, messages.WARNING,
_(u'No XLS file for your form '
u'<strong>%(id)s</strong>')
% {'id': form_id_string})
return HttpResponseRedirect("/%s" % username)
except:
return HttpResponseServerError('Error retrieving XLSForm.')
survey= Survey.from_xls(filelike_obj=xlsform_io)
zip_filename= '{}_spss_labels.zip'.format(xform.id_string)
# zip_io= survey_to_spss_label_zip(survey, xform.id_string)
# response = StreamingHttpResponse(FileWrapper(zip_io),
# content_type='application/zip; charset=utf-8')
# response['Content-Disposition'] = 'attachment; filename={}'.format(zip_filename)
# return response
return HttpResponse('Not Implemented')
示例14: app
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def app(environ, respond):
fn = os.path.join(path, environ['PATH_INFO'][1:])
if '.' not in fn.split(os.path.sep)[-1]:
fn = os.path.join(fn, 'index.html')
type = mimetypes.guess_type(fn)[0]
if os.path.exists(fn):
respond('200 OK', [('Content-Type', type)])
return util.FileWrapper(open(fn))
else:
respond('404 Not Found', [('Content-Type', 'text/plain')])
return ['not found']
示例15: get
# 需要导入模块: from wsgiref import util [as 别名]
# 或者: from wsgiref.util import FileWrapper [as 别名]
def get(self, *args, **kwargs):
# Make sure that everything has been saved.
self.temp_file.flush()
os.fsync(self.temp_file.fileno())
self.temp_file.close()
# Push CSV to user.
wrapper = FileWrapper(open(self.temp_filename))
response = HttpResponse(wrapper, content_type="text/csv")
response["Content-Disposition"] = (
"attachment; filename=%s" % self.csv_filename
)
# Sending a Content-Length header gives the user better information
# about the progress of their download.
response["Content-Length"] = os.path.getsize(self.temp_filename)
return response