本文整理汇总了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
示例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)))
示例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
示例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)
示例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, })
示例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',
)
示例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'))
示例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
示例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
示例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
示例11: file
# 需要导入模块: from django import http [as 别名]
# 或者: from django.http import FileResponse [as 别名]
def file(request):
return FileResponse(open(os.devnull, "rb"))
示例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)
示例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()
示例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)
示例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)