Python wsgiref.util.FileWrapper() Examples

The following are 30 code examples of wsgiref.util.FileWrapper(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wsgiref.util , or try the search function .
Example #1
Source File: __init__.py    From coursys with GNU General Public License v3.0 7 votes vote down vote up
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 
Example #2
Source File: request.py    From yats with MIT License 6 votes vote down vote up
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 
Example #3
Source File: test_wsgiref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: test_wsgiref.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #5
Source File: test_wsgiref.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: views.py    From mooder with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: home.py    From Mobile-Security-Framework-MobSF with GNU General Public License v3.0 6 votes vote down vote up
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('') 
Example #8
Source File: test_wsgiref.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #9
Source File: test_wsgiref.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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) 
Example #10
Source File: files.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #11
Source File: helpers.py    From InvenTree with MIT License 6 votes vote down vote up
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 
Example #12
Source File: test_wsgiref.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #13
Source File: test_wsgiref.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: test_wsgiref.py    From BinderFilter with MIT License 6 votes vote down vote up
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) 
Example #15
Source File: __init__.py    From anytask with MIT License 6 votes vote down vote up
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 
Example #16
Source File: __init__.py    From anytask with MIT License 6 votes vote down vote up
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 
Example #17
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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') 
Example #18
Source File: test_wsgiref.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #19
Source File: test_wsgiref.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #20
Source File: admin.py    From OnlineJudge with MIT License 5 votes vote down vote up
def get(self, request):
        problem_id = request.GET.get("problem_id")
        if not problem_id:
            return self.error("Parameter error, problem_id is required")
        try:
            problem = Problem.objects.get(id=problem_id)
        except Problem.DoesNotExist:
            return self.error("Problem does not exists")

        if problem.contest:
            ensure_created_by(problem.contest, request.user)
        else:
            ensure_created_by(problem, request.user)

        test_case_dir = os.path.join(settings.TEST_CASE_DIR, problem.test_case_id)
        if not os.path.isdir(test_case_dir):
            return self.error("Test case does not exists")
        name_list = self.filter_name_list(os.listdir(test_case_dir), problem.spj)
        name_list.append("info")
        file_name = os.path.join(test_case_dir, problem.test_case_id + ".zip")
        with zipfile.ZipFile(file_name, "w") as file:
            for test_case in name_list:
                file.write(f"{test_case_dir}/{test_case}", test_case)
        response = StreamingHttpResponse(FileWrapper(open(file_name, "rb")),
                                         content_type="application/octet-stream")

        response["Content-Disposition"] = f"attachment; filename=problem_{problem.id}_test_cases.zip"
        response["Content-Length"] = os.path.getsize(file_name)
        return response 
Example #21
Source File: views.py    From DjanGoat with MIT License 5 votes vote down vote up
def download(request):
    path = BASE_DIR + r"/" + request.GET.get('name', '')
    try:
        wrapper = FileWrapper(file(path))
    except:
        wrapper = None
    response = HttpResponse(wrapper,
                            content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' \
                                      % os.path.basename(path)
    response['Content-Length'] = os.path.getsize(path)
    return response 
Example #22
Source File: serve.py    From devguide with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
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'] 
Example #23
Source File: admin.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def download(modeladmin, request, selected):
    buf = StringIO('This is the content of the file')
    return StreamingHttpResponse(FileWrapper(buf)) 
Example #24
Source File: admin.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def download(modeladmin, request, selected):
    buf = StringIO('This is the content of the file')
    return StreamingHttpResponse(FileWrapper(buf)) 
Example #25
Source File: serve.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
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'] 
Example #26
Source File: serve.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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'] 
Example #27
Source File: serve.py    From android_universal with MIT License 5 votes vote down vote up
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'] 
Example #28
Source File: sendfile_streaming_backend.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sendfile(request, filename, **kwargs):
    # Respect the If-Modified-Since header.
    statobj = os.stat(filename)

    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]):
        return HttpResponseNotModified()

    response = StreamingHttpResponse(FileWrapper(open(filename, 'rb')))

    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    return response 
Example #29
Source File: serve.py    From datafari with Apache License 2.0 5 votes vote down vote up
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'] 
Example #30
Source File: views.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def get_cache_package(request, filetype):
    enforce_tile_secret_auth(request)

    filename = os.path.join(settings.CACHE_ROOT, 'package.'+filetype)
    f = open(filename, 'rb')

    f.seek(0, os.SEEK_END)
    size = f.tell()
    f.seek(0)

    content_type = 'application/' + {'tar': 'x-tar', 'tar.gz': 'gzip', 'tar.xz': 'x-xz'}[filetype]

    response = StreamingHttpResponse(FileWrapper(f), content_type=content_type)
    response['Content-Length'] = size
    return response