本文整理汇总了Python中django.http.StreamingHttpResponse类的典型用法代码示例。如果您正苦于以下问题:Python StreamingHttpResponse类的具体用法?Python StreamingHttpResponse怎么用?Python StreamingHttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StreamingHttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: comments
def comments(request, page=1):
perPage = 20
slice_start = perPage*int(page)-perPage
slice_end = perPage*int(page)
comments = Comments.objects.filter(is_removed=False).order_by('-posted')
amount = len(comments)
rowsRange = int(math.ceil(amount/float(perPage))) # amount of rows
comments = comments[slice_start:slice_end]
amount_this_page = len(comments)
if amount_this_page == 0 and int(page) != 1:
return HttpResponseRedirect("/comments/")
last_comment_id_seen = request.COOKIES.get('last_comment_id_seen', comments[0].id)
template = loader.get_template('index.html')
template_args = {
'content': 'comments.html',
'request': request,
'title': ' - Comments',
'comments': comments,
'amount': amount,
'amount_this_page': amount_this_page,
'range': [i+1 for i in range(rowsRange)],
'page': int(page),
'last_comment_id_seen': int(last_comment_id_seen),
}
response = StreamingHttpResponse(template.render(template_args, request))
if int(page) == 1:
response.set_cookie('last_comment_id_seen', comments[0].id, max_age=4320000)
return response
示例2: dispatch
def dispatch(self, request, *args, **kwargs):
response = StreamingHttpResponse(self._queue(),
mimetype='text/event-stream')
response['Cache-Control'] = 'no-cache'
response['Software'] = 'opps-liveblogging'
response.flush()
return response
示例3: download_key
def download_key(request, report, file_name):
user = request.user
if file_name:
files = FileRecord.objects.filter(Q(author=user) & Q(report__report_id=report) & Q(name=file_name))
if len(files) > 0:
if file_name == 'output_pnl.png':
ret = StreamingHttpResponse(files[0].content)
print(ret)
ret['Content-Type'] = 'image/jpeg'
elif file_name == 'output_performance.csv':
ret = []
r=files[0].content.split('\n')
regex = re.compile('\s+')
columns = regex.split(r[0].strip())
columns[0] = 'period'
for i in range(1, len(r)):
ret.append(dict(zip(columns, regex.split(r[i].strip()))))
return HttpResponse(json.dumps({'ret':ret}), content_type="application/json")
else:
ret = StreamingHttpResponse(files[0].content)
ret['Content-Type']='application/octet-stream'
return ret
else:
raise Http404("File Not Found")
else:
serializer = FileSerializer(FileRecord.objects.filter(Q(author=user) & Q(report__alpha_name=report)), many=True)
return Response(serializer.data)
示例4: generate_response
def generate_response(filepath, content_type, filename=None):
filename = filename or os.path.basename(filepath)
response = StreamingHttpResponse(export_iterator(filepath), content_type=content_type)
response['Content-Length'] = default_storage.size(filepath)
response['Content-Disposition'] = "attachment; filename=%s" % filename
response.set_cookie(key='fileDownload', value="true")
response.set_cookie(key='path', value="/")
return response
示例5: _download_file
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
示例6: finalize_response
def finalize_response(self, request, response, *args, **kwargs):
response = super(BaseRasterView, self).finalize_response(
request, response, *args, **kwargs)
# Use streaming responses for GDAL formats.
if isinstance(response.accepted_renderer,
renderers.gdal.BaseGDALRenderer):
headers = response._headers
response = StreamingHttpResponse(response.rendered_content)
response._headers = headers
return response
示例7: dispatch
def dispatch(self, request, *args, **kwargs):
self.slug = self.kwargs.get('slug')
self.event_obj = self.model.objects.get(
channel_long_slug=self.get_long_slug(), slug=self.slug)
response = StreamingHttpResponse(self._queue(),
mimetype='text/event-stream')
response['Cache-Control'] = 'no-cache'
response['Software'] = 'opps-liveblogging'
response['Access-Control-Allow-Origin'] = '*'
response.flush()
return response
示例8: get_django_response
def get_django_response(proxy_response):
"""This method is used to create an appropriate response based on the
Content-Length of the proxy_response. If the content is bigger than
MIN_STREAMING_LENGTH, which is found on utils.py,
than django.http.StreamingHttpResponse will be created,
else a django.http.HTTPResponse will be created instead
:param proxy_response: An Instance of urllib3.response.HTTPResponse that
will create an appropriate response
:returns: Returns an appropriate response based on the proxy_response
content-length
"""
status = proxy_response.status
headers = proxy_response.headers
logger.debug('Proxy response headers: %s', headers)
content_type = headers.get('Content-Type')
logger.debug('Content-Type: %s', content_type)
if should_stream(proxy_response):
logger.info('Content-Length is bigger than %s', DEFAULT_AMT)
response = StreamingHttpResponse(proxy_response.stream(DEFAULT_AMT),
status=status,
content_type=content_type)
else:
content = proxy_response.data or b''
response = HttpResponse(content, status=status,
content_type=content_type)
logger.info("Normalizing headers that aren't in IGNORE_HEADERS")
for header, value in headers.items():
if header.lower() not in IGNORE_HEADERS:
response[header.title()] = value
logger.debug('Response headers: %s', getattr(response, '_headers'))
cookies = proxy_response.headers.getlist('set-cookie')
logger.info('Checking for invalid cookies')
for cookie_string in cookies:
cookie_dict = cookie_from_string(cookie_string)
# if cookie is invalid cookie_dict will be None
if cookie_dict:
response.set_cookie(**cookie_dict)
logger.debug('Response cookies: %s', response.cookies)
return response
示例9: get_django_response
def get_django_response(proxy_response, strict_cookies=False):
"""This method is used to create an appropriate response based on the
Content-Length of the proxy_response. If the content is bigger than
MIN_STREAMING_LENGTH, which is found on utils.py,
than django.http.StreamingHttpResponse will be created,
else a django.http.HTTPResponse will be created instead
:param proxy_response: An Instance of urllib3.response.HTTPResponse that
will create an appropriate response
:param strict_cookies: Whether to only accept RFC-compliant cookies
:returns: Returns an appropriate response based on the proxy_response
content-length
"""
status = proxy_response.status
headers = proxy_response.headers
logger.debug('Proxy response headers: %s', headers)
content_type = headers.get('Content-Type')
logger.debug('Content-Type: %s', content_type)
if should_stream(proxy_response):
logger.info('Content-Length is bigger than %s', DEFAULT_AMT)
response = StreamingHttpResponse(proxy_response.stream(DEFAULT_AMT),
status=status,
content_type=content_type)
else:
content = proxy_response.data or b''
response = HttpResponse(content, status=status,
content_type=content_type)
logger.info('Normalizing response headers')
set_response_headers(response, headers)
logger.debug('Response headers: %s', getattr(response, '_headers'))
cookies = proxy_response.headers.getlist('set-cookie')
logger.info('Checking for invalid cookies')
for cookie_string in cookies:
cookie_dict = cookie_from_string(cookie_string,
strict_cookies=strict_cookies)
# if cookie is invalid cookie_dict will be None
if cookie_dict:
response.set_cookie(**cookie_dict)
logger.debug('Response cookies: %s', response.cookies)
return response
示例10: process_response
def process_response(self, request: HttpRequest,
response: StreamingHttpResponse) -> StreamingHttpResponse:
if getattr(request, "placeholder_open_graph_description", None) is not None:
assert not response.streaming
response.content = alter_content(request, response.content)
return response
示例11: process_response
def process_response(self, request: HttpRequest,
response: StreamingHttpResponse) -> StreamingHttpResponse:
def alter_content(content: bytes) -> bytes:
str_content = content.decode("utf-8")
bs = BeautifulSoup(str_content, features='lxml')
# Skip any admonition (warning) blocks, since they're
# usually something about users needing to be an
# organization administrator, and not useful for
# describing the page.
for tag in bs.find_all('div', class_="admonition"):
tag.clear()
# Find the first paragraph after that, and convert it from HTML to text.
first_paragraph_text = bs.find('p').text.replace('\n', ' ')
return content.replace(request.placeholder_open_graph_description.encode("utf-8"),
first_paragraph_text.encode("utf-8"))
def wrap_streaming_content(content: Iterable[bytes]) -> Iterable[bytes]:
for chunk in content:
yield alter_content(chunk)
if getattr(request, "placeholder_open_graph_description", None) is not None:
assert not response.streaming
response.content = alter_content(response.content)
return response
示例12: match
def match(request, match_pk, mode='response'):
"""
:mode:
response - Django response JSON
json - Dumped JSON object
python - Pure Python Dictionary
"""
data = data_match(match_pk)
def _json_response():
try:
response = JSONPResponse(
data, {}, response_mimetype(request), request.GET['callback'])
except:
response = JSONResponse(data, {}, response_mimetype(request))
return response
if mode == 'response':
response = _json_response()
response['Content-Disposition'] = 'inline; filename=files.json'
elif mode == 'sse':
def _sse_queue():
redis = Db('goalservematch', match_pk)
pubsub = redis.object().pubsub()
pubsub.subscribe(redis.key)
while True:
for m in pubsub.listen():
if m['type'] == 'message':
data = m['data'].decode('utf-8')
yield u"data: {}\n\n".format(data)
yield
time.sleep(0.5)
response = StreamingHttpResponse(_sse_queue(),
mimetype='text/event-stream')
response['Cache-Control'] = 'no-cache'
response['Software'] = 'opps-goalserve'
response.flush()
elif mode == 'json':
response = _json_response()
elif mode == 'python':
response = data
else:
response = \
"Please specify the mode argument as python, json or response"
return response
示例13: download_view
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
示例14: download_file
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
示例15: export_file
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