本文整理汇总了Python中django.http.StreamingHttpResponse.status_code方法的典型用法代码示例。如果您正苦于以下问题:Python StreamingHttpResponse.status_code方法的具体用法?Python StreamingHttpResponse.status_code怎么用?Python StreamingHttpResponse.status_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.StreamingHttpResponse
的用法示例。
在下文中一共展示了StreamingHttpResponse.status_code方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: serve
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import status_code [as 别名]
def serve(request, path, document_root=None, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
(r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_indexes`` to ``True`` if you'd like to serve a basic index
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
"""
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not part:
# Strip empty path components.
continue
drive, part = os.path.splitdrive(part)
head, part = os.path.split(part)
if part in (os.curdir, os.pardir):
# Strip '.' and '..' in path.
continue
newpath = os.path.join(newpath, part).replace('\\', '/')
if newpath and path != newpath:
return HttpResponseRedirect(newpath)
fullpath = os.path.join(document_root, newpath)
if os.path.isdir(fullpath):
if show_indexes:
return directory_index(newpath, fullpath)
raise Http404(_("Directory indexes are not allowed here."))
if not os.path.exists(fullpath):
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
statobj.st_mtime, statobj.st_size):
return HttpResponseNotModified()
content_type, encoding = mimetypes.guess_type(fullpath)
content_type = content_type or 'application/octet-stream'
ranged_file = RangedFileReader(open(fullpath, 'rb'))
response = StreamingHttpResponse(ranged_file,
content_type=content_type)
response["Last-Modified"] = http_date(statobj.st_mtime)
if stat.S_ISREG(statobj.st_mode):
size = statobj.st_size
response["Content-Length"] = size
response["Accept-Ranges"] = "bytes"
# Respect the Range header.
if "HTTP_RANGE" in request.META:
try:
ranges = parse_range_header(request.META['HTTP_RANGE'], size)
except ValueError:
ranges = None
# only handle syntactically valid headers, that are simple (no
# multipart byteranges)
if ranges is not None and len(ranges) == 1:
start, stop = ranges[0]
if stop > size:
# requested range not satisfiable
return HttpResponse(status=416)
ranged_file.start = start
ranged_file.stop = stop
response["Content-Range"] = "bytes %d-%d/%d" % (start, stop - 1, size)
response["Content-Length"] = stop - start
response.status_code = 206
if encoding:
response["Content-Encoding"] = encoding
return response
示例2: post
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import status_code [as 别名]
def post(self, request, *args, **kwargs):
vol = self.object = self.get_object()
# don't do anything if user is not logged in
if self.request.user.is_anonymous():
response = render(request, self.template_name, self.get_context_data())
response.status_code = 400 # bad request
return response
# get posted form data and use that to generate the export
export_form = self.get_form()
if export_form.is_valid():
cleaned_data = export_form.cleaned_data
# if github export is requested, make sure user has a
# github account available to use for access
if cleaned_data['github']:
try:
github.GithubApi.github_account(self.request.user)
except github.GithubAccountNotFound:
return self.render(request, error=self.github_account_msg)
# check that oauth token has sufficient permission
# to do needed export steps
gh = github.GithubApi.connect_as_user(self.request.user)
# note: repo would also work here, but currently asking for public_repo
if 'public_repo' not in gh.oauth_scopes():
return self.render(request, error=self.github_scope_msg)
else:
return self.render(request)
# determine which annotations should be loaded
if cleaned_data['annotations'] == 'user':
# annotations *by* this user
# (NOT all annotations the user can view)
annotations = vol.annotations().filter(user=request.user)
elif cleaned_data['annotations'].startswith('group:'):
# all annotations visible to a group this user belongs to
group_id = cleaned_data['annotations'][len('group:'):]
# NOTE: object not found error should not occur here,
# because only valid group ids should be valid choices
group = AnnotationGroup.objects.get(pk=group_id)
annotations = vol.annotations().visible_to_group(group)
# generate annotated tei
tei = annotate.annotated_tei(vol.generate_volume_tei(),
annotations)
# check form data to see if github repo is requested
if cleaned_data['github']:
try:
repo_url, ghpages_url = export.website_gitrepo(request.user,
cleaned_data['github_repo'], vol, tei,
page_one=cleaned_data['page_one'])
logger.info('Exported %s to GitHub repo %s for user %s',
vol.pid, repo_url, request.user.username)
# NOTE: maybe use a separate template here?
return self.render(request, repo_url=repo_url,
ghpages_url=ghpages_url, github_export=True)
except export.GithubExportException as err:
response = self.render(request, error='Export failed: %s' % err)
response.status_code = 400 # maybe?
return response
else:
# non github export: download zipfile
try:
webzipfile = export.website_zip(vol, tei,
page_one=cleaned_data['page_one'])
logger.info('Exported %s as jekyll zipfile for user %s',
vol.pid, request.user.username)
response = StreamingHttpResponse(FileWrapper(webzipfile, 8192),
content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s_annotated_jeyll_site.zip"' % \
(vol.noid)
response['Content-Length'] = os.path.getsize(webzipfile.name)
except export.ExportException as err:
# display error to user and redisplay the form
response = self.render(request, error='Export failed. %s' % err)
response.status_code = 500
# set a cookie to indicate download is complete, that can be
# used by javascript to hide a 'generating' indicator
completion_cookie_name = request.POST.get('completion-cookie',
'%s-web-export' % vol.noid)
response.set_cookie(completion_cookie_name, 'complete', max_age=10)
return response
示例3: do_request
# 需要导入模块: from django.http import StreamingHttpResponse [as 别名]
# 或者: from django.http.StreamingHttpResponse import status_code [as 别名]
#.........这里部分代码省略.........
# Only take into account request body if the request has a
# Content-Length header (we don't support chunked requests)
request_data['data'] = request
# It's better not propagate the Content-Length header as
# request processors may change final data length. In addition
# to this, the requests modules ignores the Content-Length
# header and tries to obtain data length directly from the
# data parameter. Therefore, providing this value in the len
# attribute seems to be the best option
request_data['data'].len = int(header[1])
elif header_name == 'cookie' or header_name == 'http_cookie':
cookie_parser = Cookie.SimpleCookie(str(header[1]))
del cookie_parser[settings.SESSION_COOKIE_NAME]
if settings.CSRF_COOKIE_NAME in cookie_parser:
del cookie_parser[settings.CSRF_COOKIE_NAME]
request_data['cookies'].update(cookie_parser)
elif self.http_headerRE.match(header_name) and not header_name in self.blacklisted_http_headers:
fixed_name = header_name.replace("http_", "", 1).replace('_', '-')
request_data['headers'][fixed_name] = header[1]
# Build the Via header
protocolVersion = self.protocolRE.match(request.META['SERVER_PROTOCOL'])
if protocolVersion is not None:
protocolVersion = protocolVersion.group(1)
else:
protocolVersion = '1.1'
via_header = "%s %s (Wirecloud-python-Proxy/1.1)" % (protocolVersion, get_current_domain(request))
if 'via' in request_data['headers']:
request_data['headers']['via'] += ', ' + via_header
else:
request_data['headers']['via'] = via_header
# XFF headers
if 'x-forwarded-for' in request_data['headers']:
request_data['headers']['x-forwarded-for'] += ', ' + request.META['REMOTE_ADDR']
else:
request_data['headers']['x-forwarded-for'] = request.META['REMOTE_ADDR']
request_data['headers']['x-forwarded-host'] = host
if 'x-forwarded-server' in request_data['headers']:
del request_data['headers']['x-forwarded-server']
# Pass proxy processors to the new request
try:
for processor in get_request_proxy_processors():
processor.process_request(request_data)
except ValidationError as e:
return e.get_response()
# Cookies
cookie_header_content = ', '.join([cookie_parser[key].OutputString() for key in request_data['cookies']])
if cookie_header_content != '':
request_data['headers']['Cookie'] = cookie_header_content
# Open the request
try:
res = requests.request(request_data['method'], request_data['url'], headers=request_data['headers'], data=request_data['data'], stream=True)
except requests.exceptions.HTTPError:
return HttpResponse(status=504)
except requests.exceptions.ConnectionError:
return HttpResponse(status=502)
# Build a Django response
response = StreamingHttpResponse(res.raw.stream(4096, decode_content=False))
# Set status code to the response
response.status_code = res.status_code
# Add all the headers received from the response
for header in res.headers:
header_lower = header.lower()
if header_lower == 'set-cookie':
for cookie in res.cookies:
response.set_cookie(cookie.name, value=cookie.value, expires=cookie.expires, path=cookie.path)
elif header_lower == 'via':
via_header = via_header + ', ' + res.headers[header]
elif is_valid_response_header(header_lower):
response[header] = res.headers[header]
# Pass proxy processors to the response
for processor in get_response_proxy_processors():
response = processor.process_response(request_data, response)
response['Via'] = via_header
return response