コード例 #1
0
 def test_defaults(self):
     """sendfile() takes at least request and filename."""
     request = django.test.RequestFactory().get("/fake-url")
     filename = __file__
     response = sendfile(request, filename)
     self.assertTrue(isinstance(response, DownloadResponse))
     self.assertFalse(response.attachment)
コード例 #2
0
    def get(self, request, *args, **kwargs):
        # Get document or raise HTTP404
        doc = get_object_or_404(models.Document, pk=self.kwargs.get("pk"))
        # If document is an exam or marked as non-public, require login
        if doc.dtype == doc.DTypes.EXAM or doc.public is False:
            if not self.request.user.is_authenticated:
                return redirect("%s?next=%s" % (
                    reverse("auth_login"),
                    reverse(
                        "documents:document_list",
                        kwargs={"category": slugify(doc.category.name)},
                    ),
                ))
        # Log download
        timerange = datetime.datetime.now() - datetime.timedelta(1)
        filters = {"document": doc, "timestamp__gt": timerange}
        if not models.DocumentDownload.objects.filter(**filters).exists():
            models.DocumentDownload.objects.create(document=doc)
        # Serve file
        filename = unicodedata.normalize("NFKD", doc.original_filename).encode(
            "ascii", "ignore")
        attachment = b"inline" if filename.lower().endswith(
            b".pdf") else b"attachment"
        response = sendfile(request, doc.document.path, encoding="ascii")
        # NOTE: The Content-Disposition header is much more complex with UTF-8
        # filenames, but we've made sure the filename only contains ASCII
        # above.
        response["Content-Disposition"] = b'%s; filename="%s"' % (attachment,
                                                                  filename)

        return response
コード例 #3
0
ファイル: views.py プロジェクト: benesch/django-downloadview
 def test_defaults(self):
     """sendfile() takes at least request and filename."""
     request = django.test.RequestFactory().get('/fake-url')
     filename = __file__
     response = sendfile(request, filename)
     self.assertTrue(isinstance(response, DownloadResponse))
     self.assertFalse(response.attachment)
コード例 #4
0
 def test_custom(self):
     """sendfile() accepts various arguments for response tuning."""
     request = django.test.RequestFactory().get('/fake-url')
     filename = __file__
     response = sendfile(request,
                         filename,
                         attachment=True,
                         attachment_filename='toto.txt',
                         mimetype='test/octet-stream',
                         encoding='gzip')
     self.assertTrue(isinstance(response, DownloadResponse))
     self.assertTrue(response.attachment)
     self.assertEqual(response.basename, 'toto.txt')
     self.assertEqual(response['Content-Type'],
                      'test/octet-stream; charset=utf-8')
     self.assertEqual(response.get_encoding(), 'gzip')
コード例 #5
0
ファイル: views.py プロジェクト: benesch/django-downloadview
 def test_custom(self):
     """sendfile() accepts various arguments for response tuning."""
     request = django.test.RequestFactory().get('/fake-url')
     filename = __file__
     response = sendfile(request,
                         filename,
                         attachment=True,
                         attachment_filename='toto.txt',
                         mimetype='test/octet-stream',
                         encoding='gzip')
     self.assertTrue(isinstance(response, DownloadResponse))
     self.assertTrue(response.attachment)
     self.assertEqual(response.basename, 'toto.txt')
     self.assertEqual(response['Content-Type'],
                      'test/octet-stream; charset=utf-8')
     self.assertEqual(response.get_encoding(), 'gzip')
コード例 #6
0
 def test_custom(self):
     """sendfile() accepts various arguments for response tuning."""
     request = django.test.RequestFactory().get("/fake-url")
     filename = __file__
     response = sendfile(
         request,
         filename,
         attachment=True,
         attachment_filename="toto.txt",
         mimetype="test/octet-stream",
         encoding="gzip",
     )
     self.assertTrue(isinstance(response, DownloadResponse))
     self.assertTrue(response.attachment)
     self.assertEqual(response.basename, "toto.txt")
     self.assertEqual(response["Content-Type"], "test/octet-stream; charset=utf-8")
     self.assertEqual(response.get_encoding(), "gzip")
コード例 #7
0
    def get(self, request, *args, **kwargs):
        doc = get_object_or_404(models.Document, pk=self.kwargs.get("pk"))
        if not os.path.exists(doc.document.path):
            return HttpResponseBadRequest("Document has no file attached.")
        if not doc.document.path.lower().endswith(".pdf"):
            return HttpResponseBadRequest(
                "File has to be a PDF to create a thumbnail")

        thumbnail_path = f"{doc.document.path}.png"
        if not os.path.exists(thumbnail_path):
            try:
                self.generate_thumbnail(doc.document.path, thumbnail_path)
            except subprocess.CalledProcessError as e:
                logger.error(
                    "Thumbnail for {} could not be created: {}".format(
                        doc.document.path, e))

        filename = unicodedata.normalize("NFKD", thumbnail_path)
        return sendfile(request,
                        thumbnail_path,
                        attachment=False,
                        attachment_filename=filename)
コード例 #8
0
 def test_404(self):
     """sendfile() raises Http404 if file does not exists."""
     request = django.test.RequestFactory().get("/fake-url")
     filename = "i-do-no-exist"
     with self.assertRaises(Http404):
         sendfile(request, filename)
コード例 #9
0
ファイル: views.py プロジェクト: benesch/django-downloadview
 def test_404(self):
     """sendfile() raises Http404 if file does not exists."""
     request = django.test.RequestFactory().get('/fake-url')
     filename = 'i-do-no-exist'
     with self.assertRaises(Http404):
         sendfile(request, filename)
コード例 #10
0
ファイル: views.py プロジェクト: Sirius-social/TMTM
 def get(self, request, uid, *args, **kwargs):
     content = Content.objects.filter(uid=uid, entity=settings.AGENT['entity']).first()
     if content:
         return sendfile(request, filename=os.path.join(settings.MEDIA_ROOT, content.uid))
     else:
         return Response(f'Not Found', status=404)