本文整理汇总了Python中django.http.StreamingHttpResponse.streaming_content方法的典型用法代码示例。如果您正苦于以下问题:Python StreamingHttpResponse.streaming_content方法的具体用法?Python StreamingHttpResponse.streaming_content怎么用?Python StreamingHttpResponse.streaming_content使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.StreamingHttpResponse
的用法示例。
在下文中一共展示了StreamingHttpResponse.streaming_content方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_streaming_response
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [as 别名]
def test_streaming_response(self):
r = StreamingHttpResponse(iter(['hello', 'world']))
# iterating over the response itself yields bytestring chunks.
chunks = list(r)
self.assertEqual(chunks, [b'hello', b'world'])
for chunk in chunks:
self.assertIsInstance(chunk, six.binary_type)
# and the response can only be iterated once.
self.assertEqual(list(r), [])
# even when a sequence that can be iterated many times, like a list,
# is given as content.
r = StreamingHttpResponse(['abc', 'def'])
self.assertEqual(list(r), [b'abc', b'def'])
self.assertEqual(list(r), [])
# streaming responses don't have a `content` attribute.
self.assertFalse(hasattr(r, 'content'))
# and you can't accidentally assign to a `content` attribute.
with self.assertRaises(AttributeError):
r.content = 'xyz'
# but they do have a `streaming_content` attribute.
self.assertTrue(hasattr(r, 'streaming_content'))
# that exists so we can check if a response is streaming, and wrap or
# replace the content iterator.
r.streaming_content = iter(['abc', 'def'])
r.streaming_content = (chunk.upper() for chunk in r.streaming_content)
self.assertEqual(list(r), [b'ABC', b'DEF'])
# coercing a streaming response to bytes doesn't return a complete HTTP
# message like a regular response does. it only gives us the headers.
r = StreamingHttpResponse(iter(['hello', 'world']))
self.assertEqual(
six.binary_type(r), b'Content-Type: text/html; charset=utf-8')
# and this won't consume its content.
self.assertEqual(list(r), [b'hello', b'world'])
# additional content cannot be written to the response.
r = StreamingHttpResponse(iter(['hello', 'world']))
with self.assertRaises(Exception):
r.write('!')
# and we can't tell the current position.
with self.assertRaises(Exception):
r.tell()
r = StreamingHttpResponse(iter(['hello', 'world']))
self.assertEqual(r.getvalue(), b'helloworld')
示例2: _download_file
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [as 别名]
def _download_file(request, file_path):
"""allows authorized user to download a given file"""
if check_access(request):
response = StreamingHttpResponse(content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(file_path)
file_obj = open(file_path, 'rb')
response.streaming_content = read_file_chunkwise(file_obj)
return response
示例3: dispatch
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [as 别名]
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
self.request = request
self.args = args
self.kwargs = kwargs
self.timeout = self.kwargs.get('channel')
response = HttpResponse()
response.streaming_content = self._iterator(handler)
response['Cache-Control'] = 'no-cache'
return response
示例4: export_file
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [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
file_obj = open(filepath)
response.streaming_content = _read_file_chunkwise(file_obj)
return response
else:
raise Http404
else:
raise PermissionDenied
示例5: download_view
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [as 别名]
def download_view(request):
if request.method == "GET":
return render(request, "download.html")
if request.POST["mb"] == "-1":
# Intentionally generate an exception.
_LOG.info("mb=-1 passed in.")
print(math.sqrt(-1))
buffer1k = _random_str(1023) + "/"
mb = max(int(request.POST["mb"]), 1)
ops = int(request.POST.get("ops", 0))
_LOG.info("Start generating %dMB data now (with ops=%d)...", mb, ops)
response = StreamingHttpResponse()
response["Content-Type"] = "application/binary"
response["Content-Disposition"] = 'attachment; filename="random{0}-{1}MB.bin"'.format(random.randint(10, 99), mb)
response["Content-Length"] = str(1024 * 1024 * mb)
response.streaming_content = _repeat_and_wait(buffer1k, 1024 * mb, ops)
logging.info("Passing the generator to the response.")
return response
示例6: download_file
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [as 别名]
def download_file(request, file_name):
"""allows authorized user to download a given file"""
if os.path.sep in file_name:
raise PermissionDenied()
if check_access(request):
directory = settings.DIRECTORY_DIRECTORY
#make sure that file exists within current directory
files = get_file_names(directory)
if file_name in files:
file_path = os.path.join(directory, file_name)
response = StreamingHttpResponse(mimetype='application/force-download')
response['Content-Disposition'] = 'attachment; filename=%s' % file_name
file_obj = open(os.path.join(directory, file_name))
response.streaming_content = read_file_chunkwise(file_obj)
return response
else:
raise Http404
示例7: test_streaming_response
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [as 别名]
def test_streaming_response(self):
filename = os.path.join(os.path.dirname(__file__), 'abc.txt')
# file isn't closed until we close the response.
file1 = open(filename)
r = StreamingHttpResponse(file1)
self.assertFalse(file1.closed)
r.close()
self.assertTrue(file1.closed)
# when multiple file are assigned as content, make sure they are all
# closed with the response.
file1 = open(filename)
file2 = open(filename)
r = StreamingHttpResponse(file1)
r.streaming_content = file2
self.assertFalse(file1.closed)
self.assertFalse(file2.closed)
r.close()
self.assertTrue(file1.closed)
self.assertTrue(file2.closed)
示例8: test_streaming_response
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import streaming_content [as 别名]
def test_streaming_response(self):
r = StreamingHttpResponse(iter(["hello", "world"]))
# iterating over the response itself yields bytestring chunks.
chunks = list(r)
self.assertEqual(chunks, [b"hello", b"world"])
for chunk in chunks:
self.assertIsInstance(chunk, six.binary_type)
# and the response can only be iterated once.
self.assertEqual(list(r), [])
# even when a sequence that can be iterated many times, like a list,
# is given as content.
r = StreamingHttpResponse(["abc", "def"])
self.assertEqual(list(r), [b"abc", b"def"])
self.assertEqual(list(r), [])
# iterating over Unicode strings still yields bytestring chunks.
r.streaming_content = iter(["hello", "café"])
chunks = list(r)
# '\xc3\xa9' == unichr(233).encode('utf-8')
self.assertEqual(chunks, [b"hello", b"caf\xc3\xa9"])
for chunk in chunks:
self.assertIsInstance(chunk, six.binary_type)
# streaming responses don't have a `content` attribute.
self.assertFalse(hasattr(r, "content"))
# and you can't accidentally assign to a `content` attribute.
with self.assertRaises(AttributeError):
r.content = "xyz"
# but they do have a `streaming_content` attribute.
self.assertTrue(hasattr(r, "streaming_content"))
# that exists so we can check if a response is streaming, and wrap or
# replace the content iterator.
r.streaming_content = iter(["abc", "def"])
r.streaming_content = (chunk.upper() for chunk in r.streaming_content)
self.assertEqual(list(r), [b"ABC", b"DEF"])
# coercing a streaming response to bytes doesn't return a complete HTTP
# message like a regular response does. it only gives us the headers.
r = StreamingHttpResponse(iter(["hello", "world"]))
self.assertEqual(six.binary_type(r), b"Content-Type: text/html; charset=utf-8")
# and this won't consume its content.
self.assertEqual(list(r), [b"hello", b"world"])
# additional content cannot be written to the response.
r = StreamingHttpResponse(iter(["hello", "world"]))
with self.assertRaises(Exception):
r.write("!")
# and we can't tell the current position.
with self.assertRaises(Exception):
r.tell()
r = StreamingHttpResponse(iter(["hello", "world"]))
self.assertEqual(r.getvalue(), b"helloworld")