當前位置: 首頁>>代碼示例>>Python>>正文


Python http.FileResponse方法代碼示例

本文整理匯總了Python中django.http.FileResponse方法的典型用法代碼示例。如果您正苦於以下問題:Python http.FileResponse方法的具體用法?Python http.FileResponse怎麽用?Python http.FileResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.http的用法示例。


在下文中一共展示了http.FileResponse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: serve

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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 
開發者ID:edoburu,項目名稱:django-private-storage,代碼行數:24,代碼來源:servers.py

示例2: get

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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))) 
開發者ID:dissemin,項目名稱:dissemin,代碼行數:18,代碼來源:views.py

示例3: get

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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 
開發者ID:betagouv,項目名稱:mrs,代碼行數:21,代碼來源:views.py

示例4: test_mrsfiledownloadview_security

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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) 
開發者ID:betagouv,項目名稱:mrs,代碼行數:20,代碼來源:test_mrsattachment_views.py

示例5: DownloadWord

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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, }) 
開發者ID:Ascotbe,項目名稱:Medusa,代碼行數:27,代碼來源:GenerateReport.py

示例6: get

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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',
        ) 
開發者ID:OpenTechFund,項目名稱:hypha,代碼行數:27,代碼來源:views.py

示例7: test_compressed_response

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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')) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:19,代碼來源:test_fileresponse.py

示例8: get

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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 
開發者ID:QingdaoU,項目名稱:OnlineJudge,代碼行數:18,代碼來源:admin.py

示例9: get

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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 
開發者ID:QingdaoU,項目名稱:OnlineJudge,代碼行數:19,代碼來源:admin.py

示例10: download_idea_picture

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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 
開發者ID:PacktPublishing,項目名稱:Django-3-Web-Development-Cookbook-Fourth-Edition,代碼行數:20,代碼來源:views.py

示例11: file

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
def file(request):
    return FileResponse(open(os.devnull, "rb")) 
開發者ID:korfuri,項目名稱:django-prometheus,代碼行數:4,代碼來源:views.py

示例12: download_document

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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) 
開發者ID:codeforboston,項目名稱:cornerwise,代碼行數:13,代碼來源:views.py

示例13: static

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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() 
開發者ID:offensive-hub,項目名稱:black-widow,代碼行數:14,代碼來源:index_view.py

示例14: test_detail_view

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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) 
開發者ID:edoburu,項目名稱:django-private-storage,代碼行數:39,代碼來源:test_views.py

示例15: test_private_file_view

# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import FileResponse [as 別名]
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) 
開發者ID:edoburu,項目名稱:django-private-storage,代碼行數:38,代碼來源:test_views.py


注:本文中的django.http.FileResponse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。