Python django.http.FileResponse() Examples

The following are 30 code examples of django.http.FileResponse(). 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 django.http , or try the search function .
Example #1
Source File: servers.py    From django-private-storage with Apache License 2.0 10 votes vote down vote up
def serve(private_file):
        # Support If-Last-Modified
        if sys.version_info >= (3,):
            mtime = private_file.modified_time.timestamp()
        else:
            mtime = time.mktime(private_file.modified_time.timetuple())
        size = private_file.size
        if not was_modified_since(private_file.request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, size):
            return HttpResponseNotModified()

        # As of Django 1.8, FileResponse triggers 'wsgi.file_wrapper' in Django's WSGIHandler.
        # This uses efficient file streaming, such as sendfile() in uWSGI.
        # When the WSGI container doesn't provide 'wsgi.file_wrapper', it submits the file in 4KB chunks.
        if private_file.request.method == 'HEAD':
            # Avoid reading the file at all
            response = HttpResponse()
        else:
            response = FileResponse(private_file.open())
        response['Content-Type'] = private_file.content_type
        response['Content-Length'] = size
        response["Last-Modified"] = http_date(mtime)
        return response 
Example #2
Source File: views.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 7 votes vote down vote up
def download_idea_picture(request, pk):
    idea = get_object_or_404(Idea, pk=pk)
    if idea.picture:
        filename, extension = os.path.splitext(idea.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            idea.picture.file, content_type=f"image/{extension}"
        )
        slug = slugify(idea.title)[:100]
        response["Content-Disposition"] = (
            "attachment; filename="
            f"{slug}.{extension}"
        )
    else:
        response = HttpResponseNotFound(
            content="Picture unavailable"
        )
    return response 
Example #3
Source File: servers.py    From django-private-storage with Apache License 2.0 7 votes vote down vote up
def serve(private_file):
        # This supports If-Modified-Since and sends the file in 4KB chunks
        try:
            full_path = private_file.full_path
        except NotImplementedError:
            # S3 files, fall back to streaming server
            return DjangoStreamingServer.serve(private_file)
        else:
            # Using Django's serve gives If-Modified-Since support out of the box.
            response = serve(private_file.request, full_path, document_root='/', show_indexes=False)
            if private_file.request.method == 'HEAD' and response.status_code == 200:
                # Avoid reading the file at all, copy FileResponse headers
                # This is not needed for HttpResponseNotModified(), hence the 200 code check
                head_response = HttpResponse(status=response.status_code)
                for header, value in response.items():
                    head_response[header] = value
                return head_response
            else:
                return response 
Example #4
Source File: admin.py    From OnlineJudge with MIT License 7 votes vote down vote up
def get(self, request):
        contest_id = request.GET.get("contest_id")
        if not contest_id:
            return self.error("Parameter error")
        try:
            contest = Contest.objects.get(id=contest_id)
            ensure_created_by(contest, request.user)
        except Contest.DoesNotExist:
            return self.error("Contest does not exist")

        exclude_admin = request.GET.get("exclude_admin") == "1"
        zip_path = self._dump_submissions(contest, exclude_admin)
        delete_files.send_with_options(args=(zip_path,), delay=300_000)
        resp = FileResponse(open(zip_path, "rb"))
        resp["Content-Type"] = "application/zip"
        resp["Content-Disposition"] = f"attachment;filename={os.path.basename(zip_path)}"
        return resp 
Example #5
Source File: admin.py    From OnlineJudge with MIT License 7 votes vote down vote up
def get(self, request):
        problems = Problem.objects.filter(id__in=request.data["problem_id"])
        for problem in problems:
            if problem.contest:
                ensure_created_by(problem.contest, request.user)
            else:
                ensure_created_by(problem, request.user)
        path = f"/tmp/{rand_str()}.zip"
        with zipfile.ZipFile(path, "w") as zip_file:
            for index, problem in enumerate(problems):
                self.process_one_problem(zip_file=zip_file, user=request.user, problem=problem, index=index + 1)
        delete_files.send_with_options(args=(path,), delay=300_000)
        resp = FileResponse(open(path, "rb"))
        resp["Content-Type"] = "application/zip"
        resp["Content-Disposition"] = f"attachment;filename=problem-export.zip"
        return resp 
Example #6
Source File: test_fileresponse.py    From djongo with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_compressed_response(self):
        """
        If compressed responses are served with the uncompressed Content-Type
        and a compression Content-Encoding, browsers might automatically
        uncompress the file, which is most probably not wanted.
        """
        test_tuples = (
            ('.tar.gz', 'application/gzip'),
            ('.tar.bz2', 'application/x-bzip'),
            ('.tar.xz', 'application/x-xz'),
        )
        for extension, mimetype in test_tuples:
            with self.subTest(ext=extension):
                with tempfile.NamedTemporaryFile(suffix=extension) as tmp:
                    response = FileResponse(tmp)
                self.assertEqual(response['Content-Type'], mimetype)
                self.assertFalse(response.has_header('Content-Encoding')) 
Example #7
Source File: test_fileresponse.py    From djongo with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_compressed_response(self):
        """
        If compressed responses are served with the uncompressed Content-Type
        and a compression Content-Encoding, browsers might automatically
        uncompress the file, which is most probably not wanted.
        """
        test_tuples = (
            ('.tar.gz', 'application/gzip'),
            ('.tar.bz2', 'application/x-bzip'),
            ('.tar.xz', 'application/x-xz'),
        )
        for extension, mimetype in test_tuples:
            with self.subTest(ext=extension):
                with tempfile.NamedTemporaryFile(suffix=extension) as tmp:
                    response = FileResponse(tmp)
                self.assertEqual(response['Content-Type'], mimetype)
                self.assertFalse(response.has_header('Content-Encoding')) 
Example #8
Source File: views.py    From dissemin with GNU Affero General Public License v3.0 7 votes vote down vote up
def get(self, request, pk):
        """
        We test if the user is the user that own the deposit and return a PDF file if the repository specifies this
        """
        dr = get_object_or_404(DepositRecord.objects.select_related('paper', 'repository', 'user', 'license'), pk=pk)

        if dr.user != request.user:
            raise PermissionDenied
        # If the repository requires a letter of declaration, we try to create the pdf, otherwise we return 404.
        if dr.repository.letter_declaration is not None and dr.status == "pending":
            pdf = get_declaration_pdf(dr)
            pdf.seek(0)
            filename = _("Declaration {}.pdf").format(dr.paper.title)
            return FileResponse(pdf, as_attachment=True, filename=filename)
        else:
            raise Http404(_("No pdf found for dr {}".format(dr.pk))) 
Example #9
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        content = draw_submission_content(
            self.object.output_text_answers()
        )
        pdf = make_pdf(
            title=self.object.title,
            sections=[
                {
                    'content': content,
                    'title': 'Submission',
                    'meta': [
                        self.object.stage,
                        self.object.page,
                        self.object.round,
                        f"Lead: { self.object.lead }",
                    ],
                },
            ]
        )
        return FileResponse(
            pdf,
            as_attachment=True,
            filename=self.object.title + '.pdf',
        ) 
Example #10
Source File: GenerateReport.py    From Medusa with GNU General Public License v3.0 7 votes vote down vote up
def DownloadWord(request):#下载word报告
    # 设置响应文件类型数据的响应头
    RequestLogRecord(request, request_api="download_word")
    if request.method == "POST":
        try:
            #传入Sid和Token来进行创建任务
            FileName=json.loads(request.body)["file_name"]
            UserToken=json.loads(request.body)["token"]
            Uid = UserInfo().QueryUidWithToken(UserToken)  # 如果登录成功后就来查询UID
            UserOperationLogRecord(request, request_api="download_word", uid=Uid)
            if Uid != None:  # 查到了UID
                QueryReturnValue=ReportGenerationList().Query(uid=Uid, file_name=FileName)  # 查询是否是该用户的
                if (QueryReturnValue!=None) and (QueryReturnValue!=False):
                    file = open(GetDownloadFolderLocation().Result()+FileName, 'rb')
                    response = FileResponse(file)
                    response['Content-Type'] = 'application/octet-stream'
                    response['Content-Disposition'] = 'attachment;filename='+FileName
                    return response
                else:
                    return JsonResponse({'message': '啊啊啊它不是你的,别瞎搞呀!', 'code': 404, })
        except Exception as e:
            ErrorLog().Write("Web_Api_GenerateReport_GenerateWord(def)", e)
            return JsonResponse({'message': '莎酱被玩坏啦(>^ω^<)喵', 'code': 500, })
    else:
        return JsonResponse({'message': '请使用Post请求', 'code': 500, }) 
Example #11
Source File: test_mrsattachment_views.py    From mrs with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_mrsfiledownloadview_security(srf, attachment):
    view = MRSFileDownloadView.as_view(model=MRSAttachment)
    request = srf.get('/')

    with pytest.raises(http.Http404):
        view(request, pk=attachment.id)

    request.user.profile = 'stat'
    with pytest.raises(http.Http404):
        view(request, pk=attachment.id)

    request.user.profile = None
    MRSRequest(attachment.mrsrequest_uuid).allow(request)
    response = view(request, pk=attachment.id)
    assert response.status_code == 200
    assert b''.join(response.streaming_content) == b'aoeu'
    assert response['Content-Length'] == '4'
    assert isinstance(response, http.FileResponse) 
Example #12
Source File: views.py    From mrs with GNU Affero General Public License v3.0 7 votes vote down vote up
def get(self, request, *args, **kwargs):
        path = finders.find(self.path)

        if self.stream:
            response = http.FileResponse(
                open(path, 'rb'),
                content_type=self.content_type,
            )
        else:
            with open(path, 'r', encoding='utf8') as f:
                response = http.HttpResponse(
                    f.read(),
                    content_type=self.content_type,
                )

        if self.allow_origin:
            response['Access-Control-Allow-Origin'] = self.allow_origin

        return response 
Example #13
Source File: index_view.py    From black-widow with GNU General Public License v3.0 6 votes vote down vote up
def static(request, path):
    """
    Manage requested static file (for non-DEBUG mode compatibility without web-server)
    :type request: django.core.handlers.wsgi.WSGIRequest
    :type path: str
    :rtype: django.http.HttpResponse
    """
    for directory in STATICFILES_DIRS:
        static_file = os.path.join(directory, path)
        if os.path.isfile(static_file):
            return FileResponse(open(static_file, 'rb'))
    return HttpResponseNotFound() 
Example #14
Source File: api_views.py    From zentral with Apache License 2.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        task_result = get_object_or_404(TaskResult, task_id=str(kwargs["task_id"]), status="SUCCESS")
        result = json.loads(task_result.result)
        filepath = result["filepath"]
        response = FileResponse(open(filepath, "rb"))
        for k, v in result.get("headers").items():
            response[k] = v
        return response 
Example #15
Source File: views.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def show_document(request, pk):
    """
    Show documents via django's view, not via media files
    to avoid nginx base authentication
    """
    document = Document.objects.get(pk=pk)
    file_name = document.name
    with file_storage.get_document_as_local_fn(document.source_path) as (full_name, _):
        mimetype = python_magic.from_file(full_name)
        response = FileResponse(open(full_name, 'rb'), content_type=mimetype)
        response['Content-Disposition'] = 'inline; filename="{}"'.format(file_name)
        return response 
Example #16
Source File: views.py    From django-prometheus with Apache License 2.0 6 votes vote down vote up
def file(request):
    return FileResponse(open(os.devnull, "rb")) 
Example #17
Source File: test_views.py    From django-private-storage with Apache License 2.0 6 votes vote down vote up
def test_detail_view(self):
        """
        Test the detail view that returns the object
        """
        CustomerDossier.objects.create(
            customer='cust1',
            file=SimpleUploadedFile('test4.txt', b'test4')
        )

        superuser = User.objects.create_superuser('admin', 'admin@example.com', 'admin')

        # Test HEAD calls too
        for method in ('GET', 'HEAD'):
            request = RequestFactory().generic(method, '/cust1/file/')
            request.user = superuser

            # Initialize locally, no need for urls.py etc..
            # This behaves like a standard DetailView
            view = PrivateStorageDetailView.as_view(
                model=CustomerDossier,
                slug_url_kwarg='customer',
                slug_field='customer',
                model_file_field='file'
            )

            response = view(
                request,
                customer='cust1',
            )
            if method == 'HEAD':
                self.assertNotIsInstance(response, FileResponse)
                self.assertEqual(response.content, b'')
            else:
                self.assertEqual(list(response.streaming_content), [b'test4'])
            self.assertEqual(response['Content-Type'], 'text/plain')
            self.assertEqual(response['Content-Length'], '5')
            self.assertIn('Last-Modified', response) 
Example #18
Source File: test_views.py    From django-private-storage with Apache License 2.0 6 votes vote down vote up
def test_private_file_view(self):
        """
        Test the detail view that returns the object
        """
        obj = CustomerDossier.objects.create(
            customer='cust2',
            file=SimpleUploadedFile('test5.txt', b'test5')
        )
        self.assertExists('CustomerDossier', 'cust2', 'test5.txt')

        # Initialize locally, no need for urls.py etc..
        # This behaves like a standard DetailView
        view = PrivateStorageView.as_view(
            content_disposition='attachment',
        )
        superuser = User.objects.create_superuser('admin', 'admin@example.com', 'admin')

        # Test HEAD calls too
        for method in ('GET', 'HEAD'):
            request = RequestFactory().generic(method, '/cust1/file/')
            request.user = superuser
            request.META['HTTP_USER_AGENT'] = 'Test'

            response = view(
                request,
                path='CustomerDossier/cust2/test5.txt'
            )
            if method == 'HEAD':
                self.assertNotIsInstance(response, FileResponse)
                self.assertEqual(response.content, b'')
            else:
                self.assertEqual(list(response.streaming_content), [b'test5'])
            self.assertEqual(response['Content-Type'], 'text/plain')
            self.assertEqual(response['Content-Length'], '5')
            self.assertEqual(response['Content-Disposition'], "attachment; filename*=UTF-8''test5.txt")
            self.assertIn('Last-Modified', response) 
Example #19
Source File: test_views.py    From django-private-storage with Apache License 2.0 6 votes vote down vote up
def test_private_file_view_utf8(self):
        """
        Test the detail view that returns the object
        """
        obj = CustomerDossier.objects.create(
            customer='cust2',
            file=SimpleUploadedFile(u'Heizölrückstoßabdämpfung.txt', b'test5')
        )
        self.assertExists('CustomerDossier', 'cust2', u'Heizölrückstoßabdämpfung.txt')

        # Initialize locally, no need for urls.py etc..
        # This behaves like a standard DetailView
        view = PrivateStorageView.as_view(
            content_disposition='attachment',
        )
        superuser = User.objects.create_superuser('admin', 'admin@example.com', 'admin')

        for user_agent, expect_header in [
                ('Firefox', "attachment; filename*=UTF-8''Heiz%C3%B6lr%C3%BCcksto%C3%9Fabd%C3%A4mpfung.txt"),
                ('WebKit', 'attachment; filename=Heiz\xc3\xb6lr\xc3\xbccksto\xc3\x9fabd\xc3\xa4mpfung.txt'),
                ('MSIE', 'attachment; filename=Heiz%C3%B6lr%C3%BCcksto%C3%9Fabd%C3%A4mpfung.txt'),
                ]:

            for method in ('GET', 'HEAD'):
                request = RequestFactory().generic(method, '/cust1/file/')
                request.user = superuser
                request.META['HTTP_USER_AGENT'] = user_agent

                response = view(
                    request,
                    path=u'CustomerDossier/cust2/Heizölrückstoßabdämpfung.txt'
                )
                if method == 'HEAD':
                    self.assertNotIsInstance(response, FileResponse)
                    self.assertEqual(response.content, b'')
                else:
                    self.assertEqual(list(response.streaming_content), [b'test5'])
                self.assertEqual(response['Content-Type'], 'text/plain')
                self.assertEqual(response['Content-Length'], '5')
                self.assertEqual(response['Content-Disposition'], expect_header, user_agent)
                self.assertIn('Last-Modified', response) 
Example #20
Source File: views.py    From BioQueue with Apache License 2.0 6 votes vote down vote up
def download(file_path):
    try:
        response = FileResponse(open(file_path, 'rb'))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(os.path.basename(file_path))
        response['Content-Length'] = os.path.getsize(file_path)
        return response
    except Exception as e:
        return error(e) 
Example #21
Source File: views.py    From cornerwise with MIT License 6 votes vote down vote up
def download_document(req, pk):
    doc = get_object_or_404(Document, pk=pk)

    if not doc.document:
        return {}

    if settings.IS_PRODUCTION:
        # Serve the file using mod_xsendfile
        pass

    return FileResponse(doc.document) 
Example #22
Source File: views.py    From mrs with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        if 'wsgi.file_wrapper' in request.environ:
            del request.environ['wsgi.file_wrapper']

        self.object = self.get_object()
        f = io.BytesIO(self.object.attachment_file.read())
        content_type = self.object.mimetype or 'application/octet-stream'
        response = http.FileResponse(f, content_type=content_type)
        if self.object.encoding:
            response['Content-Encoding'] = self.object.encoding
        response['Content-Length'] = self.object.attachment_file.size
        response['Cache-Control'] = 'public, max-age=31536000'
        return response 
Example #23
Source File: generics.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def finalize_response(self, request, response, *args, **kwargs):
        response = super(BaseRasterView, self).finalize_response(
            request, response, *args, **kwargs)
        # Use streaming file responses for GDAL formats.
        if isinstance(getattr(response, 'accepted_renderer', None),
                      renderers.gdal.BaseGDALRenderer):
            headers = response._headers
            response = FileResponse(response.rendered_content)
            response._headers = headers
        return response 
Example #24
Source File: views.py    From WCnife with MIT License 6 votes vote down vote up
def download(request):
    url = request.session.get("url")
    pwd = request.session.get("pwd")
    s = SendCode(url=url, pwd=pwd)
    filename = request.GET.get('filename')
    filepath = request.session.get('now_path') + '/' + filename
    now_filepath = s.getFile(filename, filepath)
    file = open(now_filepath, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="%s"' % filename
    return response 
Example #25
Source File: test_fileresponse.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_file_from_buffer_response(self):
        response = FileResponse(io.BytesIO(b'binary content'))
        self.assertEqual(response['Content-Length'], '14')
        self.assertEqual(response['Content-Type'], 'application/octet-stream')
        self.assertEqual(list(response), [b'binary content']) 
Example #26
Source File: utils.py    From zentral with Apache License 2.0 5 votes vote down vote up
def build_application_download_response(command_uuid):
    device_artifact_command = get_object_or_404(DeviceArtifactCommand, command__uuid=command_uuid)
    package_file = device_artifact_command.artifact.file
    response = FileResponse(package_file, content_type="application/octet-stream")
    response["Content-Length"] = package_file.size
    response["Content-Disposition"] = 'attachment;filename="{}"'.format(os.path.basename(package_file.name))
    return response


# process result payload 
Example #27
Source File: setup.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        dep_token = get_object_or_404(DEPToken, pk=kwargs["pk"], consumer_key__isnull=True)
        certificate = dep_token.certificate
        if isinstance(certificate, memoryview):
            certificate = certificate.tobytes()
        filename = "{}_public_key_{}_{}.pem".format(
            request.get_host(),
            dep_token.pk,
            dep_token.created_at.strftime("%Y%m%d%H%M%S")
        )
        return FileResponse(io.BytesIO(certificate),
                            content_type="application/x-pem-file",
                            as_attachment=True,
                            filename=filename) 
Example #28
Source File: builder.py    From zentral with Apache License 2.0 5 votes vote down vote up
def build_and_make_response(self):
        template_path = os.path.join(BASE_DIR, "template.py")
        with open(template_path, "r") as f:
            content = f.read()

        # tls hostname
        tls_hostname = self.get_tls_hostname()
        content = content.replace("%TLS_HOSTNAME%", tls_hostname)
        content = content.replace("%TLS_HOSTNAME_FOR_CLIENT_CERT_AUTH%",
                                  self.get_tls_hostname(for_client_cert_auth=True))

        # tls server certs
        tls_server_certs_path = self.get_tls_server_certs()
        if tls_server_certs_path:
            with open(tls_server_certs_path, "r") as f:
                tls_server_certs = f.read()
        else:
            tls_server_certs = ""
        content = content.replace("%TLS_SERVER_CERTS%", tls_server_certs)

        # enrollment secret
        content = content.replace("%ENROLLMENT_SECRET%", self.enrollment_secret)

        # filebeat release
        content = content.replace("%FILEBEAT_VERSION%", self.filebeat_release)

        return FileResponse(
            io.BytesIO(content.encode("utf-8")), content_type="text/x-python",
            as_attachment=True,
            filename=self.script_name_tmpl.format(tls_hostname)
        ) 
Example #29
Source File: test_fileresponse.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_file_from_disk_as_attachment(self):
        response = FileResponse(open(__file__, 'rb'), as_attachment=True)
        self.assertEqual(response['Content-Length'], str(os.path.getsize(__file__)))
        self.assertIn(response['Content-Type'], ['text/x-python', 'text/plain'])
        self.assertEqual(response['Content-Disposition'], 'attachment; filename="test_fileresponse.py"')
        response.close() 
Example #30
Source File: test_fileresponse.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_file_from_named_pipe_response(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            pipe_file = os.path.join(temp_dir, 'named_pipe')
            os.mkfifo(pipe_file)
            pipe_for_read = os.open(pipe_file, os.O_RDONLY | os.O_NONBLOCK)
            with open(pipe_file, 'wb') as pipe_for_write:
                pipe_for_write.write(b'binary content')

            response = FileResponse(os.fdopen(pipe_for_read, mode='rb'))
            self.assertEqual(list(response), [b'binary content'])
            response.close()
            self.assertFalse(response.has_header('Content-Length'))