本文整理匯總了Python中django.http.StreamingHttpResponse方法的典型用法代碼示例。如果您正苦於以下問題:Python http.StreamingHttpResponse方法的具體用法?Python http.StreamingHttpResponse怎麽用?Python http.StreamingHttpResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.http
的用法示例。
在下文中一共展示了http.StreamingHttpResponse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _stream_file
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def _stream_file(request, path):
# based on https://gist.github.com/dcwatson/cb5d8157a8fa5a4a046e
content_type = 'application/octet-stream'
range_header = request.META.get('HTTP_RANGE', None)
if range_header:
range_match = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I).match(range_header)
first_byte, last_byte = range_match.groups()
first_byte = int(first_byte) if first_byte else 0
last_byte = int(last_byte)
length = last_byte - first_byte + 1
resp = StreamingHttpResponse(
file_iter(path, byte_range=(first_byte, last_byte)), status=206, content_type=content_type)
resp['Content-Length'] = str(length)
resp['Content-Range'] = 'bytes %s-%s' % (first_byte, last_byte)
else:
resp = StreamingHttpResponse(file_iter(path), content_type=content_type)
resp['Accept-Ranges'] = 'bytes'
return resp
示例2: submitted_file
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def submitted_file(request: HttpRequest, course_slug: str, activity_slug: str, userid: str, answer_id: str, secret: str) -> StreamingHttpResponse:
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug)
answer = get_object_or_404(QuestionAnswer, question__quiz__activity=activity, student=member, id=answer_id)
real_secret = answer.answer['data'].get('secret', '?')
if real_secret != '?' and secret == real_secret:
return _return_submitted_file(answer.answer['data'], answer.file.open('rb'))
else:
# It's not the current submission, but an instructor looking at history might be trying to find an old one...
submissions = QuizSubmission.objects.filter(quiz__activity=activity, student=member)
for qs in submissions:
for answer_config in qs.config['answers']:
version_id, answer_id, a = answer_config
if not isinstance(a['data'], dict):
continue
real_secret = a['data'].get('secret', '?')
if answer.question_version_id == version_id and answer.id == answer_id and real_secret != '?' and secret == real_secret:
# aha! Temporarily replace answer.file with the old version (without saving) so we can return it
answer.file = a['filepath']
return _return_submitted_file(a['data'], answer.file.open('rb'))
raise Http404()
示例3: view_attachment
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def view_attachment(request, userid, event_slug, attach_slug):
person, member_units = _get_faculty_or_404(request.units, userid)
event = _get_event_or_404(units=request.units, slug=event_slug, person=person)
viewer = get_object_or_404(Person, userid=request.user.username)
attachment = get_object_or_404(event.attachments.all(), slug=attach_slug)
handler = event.get_handler()
if not handler.can_view(viewer):
raise PermissionDenied("Not allowed to view this attachment")
filename = attachment.contents.name.rsplit('/')[-1]
resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
resp['Content-Disposition'] = 'inline; filename="' + filename + '"'
resp['Content-Length'] = attachment.contents.size
return resp
示例4: download_attachment
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def download_attachment(request, userid, event_slug, attach_slug):
person, member_units = _get_faculty_or_404(request.units, userid)
event = _get_event_or_404(units=request.units, slug=event_slug, person=person)
viewer = get_object_or_404(Person, userid=request.user.username)
attachment = get_object_or_404(event.attachments.all(), slug=attach_slug)
handler = event.get_handler()
if not handler.can_view(viewer):
raise PermissionDenied("Not allowed to download this attachment")
filename = attachment.contents.name.rsplit('/')[-1]
resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
resp['Content-Length'] = attachment.contents.size
return resp
示例5: render_to_response
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def render_to_response(self, context, **response_kwargs):
"""
Returns a response containing the exported CSV of selected targets.
:param context: Context object for this view
:type context: dict
:returns: response class with CSV
:rtype: StreamingHttpResponse
"""
qs = context['filter'].qs.values()
file_buffer = export_targets(qs)
file_buffer.seek(0) # goto the beginning of the buffer
response = StreamingHttpResponse(file_buffer, content_type="text/csv")
filename = "targets-{}.csv".format(slugify(datetime.utcnow()))
response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
return response
示例6: export_protocol
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def export_protocol(request):
if request.method == 'GET':
if 'id' in request.GET:
pname, protocol_text = build_plain_protocol(request, request.GET['id'])
if protocol_text == 1:
return error('Cannot find the protocol.')
elif protocol_text == 2:
return error('You are not owner of the protocol.')
else:
from django.http import StreamingHttpResponse
response = StreamingHttpResponse(protocol_text)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(str(pname + '.txt'))
return response
else:
return error('Unknown parameter.')
else:
return error('Method error.')
示例7: DownloadFile
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
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
示例8: serve_file
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def serve_file(request, file_to_serve, article, public=False, hide_name=False):
"""Serve a file to the user using a StreamingHttpResponse.
:param request: the active request
:param file_to_serve: the file object to retrieve and serve
:param article: the associated article
:param public: boolean
:param hide_name: boolean
:return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or
permission error
"""
path_parts = ('articles', article.pk)
return serve_any_file(
request,
file_to_serve,
public,
hide_name=hide_name,
path_parts=path_parts
)
示例9: serve_journal_cover
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def serve_journal_cover(request, file_to_serve):
"""Serve a file to the user using a StreamingHttpResponse.
:param request: the active request
:param file_to_serve: the file object to retrieve and serve
:return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or
permission error
"""
file_path = os.path.join(settings.BASE_DIR, 'files', 'journals', str(request.journal.id),
str(file_to_serve.uuid_filename))
try:
response = serve_file_to_browser(file_path, file_to_serve)
return response
except IOError:
messages.add_message(request, messages.ERROR, 'File not found. {0}'.format(file_path))
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
示例10: serve_press_cover
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def serve_press_cover(request, file_to_serve):
"""Serve a file to the user using a StreamingHttpResponse.
:param request: the active request
:param file_to_serve: the file to serve
:return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or
permission error
"""
file_path = os.path.join(settings.BASE_DIR, 'files', 'press', str(file_to_serve.uuid_filename))
try:
response = serve_file_to_browser(file_path, file_to_serve)
return response
except IOError:
messages.add_message(request, messages.ERROR, 'File not found. {0}'.format(file_path))
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
示例11: get
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def get(self, request, user, resource_name):
resource = self.get_resource(request, user, resource_name)
if resource.collection:
return HttpResponseForbidden()
response = StreamingHttpResponse(
self.storage.retrieve(
self, request, resource
),
content_type=resource.content_type
)
response['Content-Length'] = resource.size
response[
'Content-Disposition'] = "attachment; filename=%s" % resource.name
return response
示例12: export_file
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def export_file(request, pk, file_name):
"""
Allows authorized user to export a file.
Adapted from https://github.com/ASKBOT/django-directory
"""
export = get_object_or_404(Export, pk=pk)
if (request.user == export.user) or request.user.is_superuser:
filepath = os.path.join(export.path, file_name)
log.debug("Exporting %s", filepath)
if os.path.exists(filepath):
response = StreamingHttpResponse()
response['Content-Disposition'] = 'attachment; filename=%s' % file_name
response['Content-Type'] = 'application/octet-stream'
file_obj = open(filepath, 'rb')
response.streaming_content = _read_file_chunkwise(file_obj)
return response
else:
raise Http404
else:
raise PermissionDenied
示例13: export
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def export(self):
"""
A helper method called when ``_export`` is present in ``request.GET``. Returns a ``StreamingHttpResponse``
that yields CSV data for all matching results.
"""
keywords = self.get_keywords()
facets = self.get_facet_data()
search = self.get_search(keywords, facets, aggregate=False)
columns = self.get_columns()
def csv_escape(value):
if isinstance(value, (list, tuple)):
value = '; '.join(force_text(v) for v in value)
return '"%s"' % force_text(value).replace('"', '""')
def csv_generator():
yield ','.join('"%s"' % c.label for c in columns if c.visible and c.export) + '\n'
for result in search.scan():
yield ','.join(csv_escape(c.export_value(result)) for c in columns if c.visible and c.export) + '\n'
export_timestamp = ('_' + timezone.now().strftime('%m-%d-%Y_%H-%M-%S')) if self.export_timestamp else ''
export_name = '%s%s.csv' % (self.export_name, export_timestamp)
resp = StreamingHttpResponse(csv_generator(), content_type='text/csv; charset=utf-8')
resp['Content-Disposition'] = 'attachment; filename=%s' % export_name
return resp
示例14: get
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
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
示例15: get_csv_response
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import StreamingHttpResponse [as 別名]
def get_csv_response(queryset: QuerySet,
fields: dict,
title: str) -> StreamingHttpResponse:
writer = csv.writer(PassthroughIO())
# Nest field names into an iterable of 1 so it can be chained.
# Add in our two foreign key traversals by name.
headers = [fields.keys()]
data = (row_helper(item, fields) for item in queryset)
# Chain the headers and the data into a single iterator.
generator = (writer.writerow(row) for row in itertools.chain(headers, data))
# Streaming responses require a generator; which is good, as it can
# process machines one by one rather than shoving the entire output
# into memory.
response = StreamingHttpResponse(generator, content_type="text/csv")
# If DEBUG_CSV is enabled, just print output rather than download.
if not server.utils.get_django_setting('DEBUG_CSV', False):
response['Content-Disposition'] = 'attachment; filename="%s.csv"' % title
return response