当前位置: 首页>>代码示例>>Python>>正文


Python util.FileWrapper方法代码示例

本文整理汇总了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 
开发者ID:sfu-fas,项目名称:coursys,代码行数:22,代码来源:__init__.py

示例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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:19,代码来源:test_wsgiref.py

示例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 
开发者ID:znick,项目名称:anytask,代码行数:21,代码来源:__init__.py

示例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 
开发者ID:inventree,项目名称:InvenTree,代码行数:26,代码来源:helpers.py

示例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 
开发者ID:BirkbeckCTP,项目名称:janeway,代码行数:27,代码来源:files.py

示例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('') 
开发者ID:MobSF,项目名称:Mobile-Security-Framework-MobSF,代码行数:26,代码来源:home.py

示例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) 
开发者ID:ofermend,项目名称:medicare-demo,代码行数:19,代码来源:test_wsgiref.py

示例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 
开发者ID:phith0n,项目名称:mooder,代码行数:23,代码来源:views.py

示例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 
开发者ID:mediafactory,项目名称:yats,代码行数:24,代码来源:request.py

示例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'] 
开发者ID:mlouielu,项目名称:twstock,代码行数:15,代码来源:serve.py

示例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)) 
开发者ID:fpsw,项目名称:Servo,代码行数:5,代码来源:admin.py

示例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 
开发者ID:sfu-fas,项目名称:coursys,代码行数:34,代码来源:__init__.py

示例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') 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:32,代码来源:views.py

示例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'] 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:15,代码来源:serve.py

示例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 
开发者ID:pydata,项目名称:conf_site,代码行数:17,代码来源:views.py


注:本文中的wsgiref.util.FileWrapper方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。