本文整理汇总了Python中swift.common.swob.Response.status方法的典型用法代码示例。如果您正苦于以下问题:Python Response.status方法的具体用法?Python Response.status怎么用?Python Response.status使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类swift.common.swob.Response
的用法示例。
在下文中一共展示了Response.status方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: best_response
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def best_response(self, req, statuses, reasons, bodies, server_type,
etag=None, headers=None):
"""
Given a list of responses from several servers, choose the best to
return to the API.
:param req: swob.Request object
:param statuses: list of statuses returned
:param reasons: list of reasons for each status
:param bodies: bodies of each response
:param server_type: type of server the responses came from
:param etag: etag
:param headers: headers of each response
:returns: swob.Response object with the correct status, body, etc. set
"""
resp = Response(request=req)
if len(statuses):
for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
hstatuses = \
[s for s in statuses if hundred <= s < hundred + 100]
if len(hstatuses) >= quorum_size(len(statuses)):
status = max(hstatuses)
status_index = statuses.index(status)
resp.status = '%s %s' % (status, reasons[status_index])
resp.body = bodies[status_index]
if headers:
update_headers(resp, headers[status_index])
if etag:
resp.headers['etag'] = etag.strip('"')
return resp
self.app.logger.error(_('%(type)s returning 503 for %(statuses)s'),
{'type': server_type, 'statuses': statuses})
resp.status = '503 Internal Server Error'
return resp
示例2: best_response
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def best_response(self, req, statuses, reasons, bodies, server_type, etag=None):
"""
Given a list of responses from several servers, choose the best to
return to the API.
:param req: swob.Request object
:param statuses: list of statuses returned
:param reasons: list of reasons for each status
:param bodies: bodies of each response
:param server_type: type of server the responses came from
:param etag: etag
:returns: swob.Response object with the correct status, body, etc. set
"""
resp = Response(request=req)
if len(statuses):
for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
hstatuses = [s for s in statuses if hundred <= s < hundred + 100]
if len(hstatuses) > len(statuses) / 2:
status = max(hstatuses)
status_index = statuses.index(status)
resp.status = "%s %s" % (status, reasons[status_index])
resp.body = bodies[status_index]
if etag:
resp.headers["etag"] = etag.strip('"')
return resp
self.app.logger.error(_("%(type)s returning 503 for %(statuses)s"), {"type": server_type, "statuses": statuses})
resp.status = "503 Internal Server Error"
return resp
示例3: PUT
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def PUT(self, env, start_response):
"""
Handle PUT Bucket request
"""
if 'HTTP_X_AMZ_ACL' in env:
amz_acl = env['HTTP_X_AMZ_ACL']
# Translate the Amazon ACL to something that can be
# implemented in Swift, 501 otherwise. Swift uses POST
# for ACLs, whereas S3 uses PUT.
del env['HTTP_X_AMZ_ACL']
if 'QUERY_STRING' in env:
del env['QUERY_STRING']
translated_acl = swift_acl_translate(amz_acl)
if translated_acl == 'Unsupported':
return get_err_response('Unsupported')
elif translated_acl == 'InvalidArgument':
return get_err_response('InvalidArgument')
for header, acl in translated_acl:
env[header] = acl
if 'CONTENT_LENGTH' in env:
content_length = env['CONTENT_LENGTH']
try:
content_length = int(content_length)
except (ValueError, TypeError):
return get_err_response('InvalidArgument')
if content_length < 0:
return get_err_response('InvalidArgument')
if 'QUERY_STRING' in env:
args = dict(urlparse.parse_qsl(env['QUERY_STRING'], 1))
if 'acl' in args:
# We very likely have an XML-based ACL request.
body = env['wsgi.input'].readline().decode()
translated_acl = swift_acl_translate(body, xml=True)
if translated_acl == 'Unsupported':
return get_err_response('Unsupported')
elif translated_acl == 'InvalidArgument':
return get_err_response('InvalidArgument')
for header, acl in translated_acl:
env[header] = acl
env['REQUEST_METHOD'] = 'POST'
body_iter = self._app_call(env)
status = self._get_status_int()
if status != HTTP_CREATED and status != HTTP_NO_CONTENT:
if status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN):
return get_err_response('AccessDenied')
elif status == HTTP_ACCEPTED:
return get_err_response('BucketAlreadyExists')
else:
return get_err_response('InvalidURI')
resp = Response()
resp.headers['Location'] = self.container_name
resp.status = HTTP_OK
return resp
示例4: page_obj_list
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def page_obj_list(self, req, storage_url, token, template=None):
""" """
if template is None:
tmpl = self.tmpl
path = urlparse(self.del_prefix(req.url)).path
if len(path.split('/')) <= 2:
path = urlparse(storage_url).path
vrs, acc, cont, obj = split_path(path, 1, 4, True)
lang = self.get_lang(req)
base = self.add_prefix(urlparse(storage_url).path)
status = self.token_bank.get(token, None)
msg = status.get('msg', '') if status else ''
params = req.params_alt()
limit = params.get('limit', self.items_per_page)
marker = params.get('marker', '')
end_marker = params.get('end_marker', '')
prefix = params.get('prefix', '')
delete_confirm = quote(params.get('delete_confirm', ''))
acl_edit = quote(params.get('acl_edit', ''))
meta_edit = quote(params.get('meta_edit', ''))
# whole container list
try:
whole_cont_list = self._get_whole_cont_list(storage_url, token)
except ClientException, err:
resp = Response(charset='utf8')
resp.status = err.http_status
return resp
示例5: OPTIONS
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def OPTIONS(self, req):
"""
Base handler for OPTIONS requests
:param req: swob.Request object
:returns: swob.Response object
"""
# Prepare the default response
headers = {'Allow': ', '.join(self.allowed_methods)}
resp = Response(status=200, request=req, headers=headers)
# If this isn't a CORS pre-flight request then return now
req_origin_value = req.headers.get('Origin', None)
if not req_origin_value:
return resp
# This is a CORS preflight request so check it's allowed
try:
container_info = \
self.container_info(self.account_name,
self.container_name, req)
except AttributeError:
# This should only happen for requests to the Account. A future
# change could allow CORS requests to the Account level as well.
return resp
cors = container_info.get('cors', {})
# If the CORS origin isn't allowed return a 401
if not self.is_origin_allowed(cors, req_origin_value) or (
req.headers.get('Access-Control-Request-Method') not in
self.allowed_methods):
resp.status = HTTP_UNAUTHORIZED
return resp
# Allow all headers requested in the request. The CORS
# specification does leave the door open for this, as mentioned in
# http://www.w3.org/TR/cors/#resource-preflight-requests
# Note: Since the list of headers can be unbounded
# simply returning headers can be enough.
allow_headers = set()
if req.headers.get('Access-Control-Request-Headers'):
allow_headers.update(
list_from_csv(req.headers['Access-Control-Request-Headers']))
# Populate the response with the CORS preflight headers
if cors.get('allow_origin', '').strip() == '*':
headers['access-control-allow-origin'] = '*'
else:
headers['access-control-allow-origin'] = req_origin_value
if cors.get('max_age') is not None:
headers['access-control-max-age'] = cors.get('max_age')
headers['access-control-allow-methods'] = \
', '.join(self.allowed_methods)
if allow_headers:
headers['access-control-allow-headers'] = ', '.join(allow_headers)
resp.headers = headers
return resp
示例6: get_err_response
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def get_err_response(self, msg="Unable to process requested file"):
self.logger.error(msg)
resp = Response(content_type="text/xml")
resp.status = HTTP_BAD_REQUEST
resp.body = (
'<?xml version="1.0" encoding="UTF-8"?>\r\n<Error>\r\n '
"<Code>%s</Code>\r\n <Message>%s</Message>\r\n</Error>\r\n" % (HTTP_BAD_REQUEST, msg)
)
return resp
示例7: OPTIONS
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def OPTIONS(self, req):
"""
Base handler for OPTIONS requests
:param req: swob.Request object
:returns: swob.Response object
"""
# Prepare the default response
headers = {'Allow': ', '.join(self.allowed_methods)}
resp = Response(status=200, request=req, headers=headers)
# If this isn't a CORS pre-flight request then return now
req_origin_value = req.headers.get('Origin', None)
if not req_origin_value:
return resp
# This is a CORS preflight request so check it's allowed
try:
container_info = \
self.container_info(self.account_name, self.container_name)
except AttributeError:
# This should only happen for requests to the Account. A future
# change could allow CORS requests to the Account level as well.
return resp
cors = container_info.get('cors', {})
# If the CORS origin isn't allowed return a 401
if not self.is_origin_allowed(cors, req_origin_value) or (
req.headers.get('Access-Control-Request-Method') not in
self.allowed_methods):
resp.status = HTTP_UNAUTHORIZED
return resp
# Always allow the x-auth-token header. This ensures
# clients can always make a request to the resource.
allow_headers = set()
if cors.get('allow_headers'):
allow_headers.update(
[a.strip()
for a in cors['allow_headers'].split(' ')
if a.strip()])
allow_headers.add('x-auth-token')
# Populate the response with the CORS preflight headers
headers['access-control-allow-origin'] = req_origin_value
if cors.get('max_age') is not None:
headers['access-control-max-age'] = cors.get('max_age')
headers['access-control-allow-methods'] = \
', '.join(self.allowed_methods)
headers['access-control-allow-headers'] = ', '.join(allow_headers)
resp.headers = headers
return resp
示例8: get_err_response
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def get_err_response(code):
"""
Given an HTTP response code, create a properly formatted xml error response
:param code: error code
:returns: webob.response object
"""
error_table = {
'AccessDenied':
(HTTP_FORBIDDEN, 'Access denied'),
'BucketAlreadyExists':
(HTTP_CONFLICT, 'The requested bucket name is not available'),
'BucketNotEmpty':
(HTTP_CONFLICT, 'The bucket you tried to delete is not empty'),
'InvalidArgument':
(HTTP_BAD_REQUEST, 'Invalid Argument'),
'InvalidBucketName':
(HTTP_BAD_REQUEST, 'The specified bucket is not valid'),
'InvalidURI':
(HTTP_BAD_REQUEST, 'Could not parse the specified URI'),
'InvalidDigest':
(HTTP_BAD_REQUEST, 'The Content-MD5 you specified was invalid'),
'BadDigest':
(HTTP_BAD_REQUEST, 'The Content-Length you specified was invalid'),
'NoSuchBucket':
(HTTP_NOT_FOUND, 'The specified bucket does not exist'),
'SignatureDoesNotMatch':
(HTTP_FORBIDDEN, 'The calculated request signature does not '
'match your provided one'),
'RequestTimeTooSkewed':
(HTTP_FORBIDDEN, 'The difference between the request time and the'
' current time is too large'),
'NoSuchKey':
(HTTP_NOT_FOUND, 'The resource you requested does not exist'),
'Unsupported':
(HTTP_NOT_IMPLEMENTED, 'The feature you requested is not yet'
' implemented'),
'MissingContentLength':
(HTTP_LENGTH_REQUIRED, 'Length Required'),
'ServiceUnavailable':
(HTTP_SERVICE_UNAVAILABLE, 'Please reduce your request rate'),
'IllegalVersioningConfigurationException':
(HTTP_BAD_REQUEST, 'The specified versioning configuration invalid'),
'MalformedACLError':
(HTTP_BAD_REQUEST, 'The XML you provided was not well-formed or did '
'not validate against our published schema')
}
resp = Response(content_type='text/xml')
resp.status = error_table[code][0]
resp.body = '<?xml version="1.0" encoding="UTF-8"?>\r\n<Error>\r\n ' \
'<Code>%s</Code>\r\n <Message>%s</Message>\r\n</Error>\r\n' \
% (code, error_table[code][1])
return resp
示例9: _deny_request
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def _deny_request(self, code):
error_table = {
'AccessDenied': (401, 'Access denied'),
'InvalidURI': (400, 'Could not parse the specified URI'),
}
resp = Response(content_type='text/xml')
resp.status = error_table[code][0]
error_msg = ('<?xml version="1.0" encoding="UTF-8"?>\r\n'
'<Error>\r\n <Code>%s</Code>\r\n '
'<Message>%s</Message>\r\n</Error>\r\n' %
(code, error_table[code][1]))
if six.PY3:
error_msg = error_msg.encode()
resp.body = error_msg
return resp
示例10: get_err_response
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def get_err_response(code):
"""
Given an HTTP response code, create a properly formatted xml error response
:param code: error code
:returns: webob.response object
"""
error_table = {
'AccessDenied': (HTTP_FORBIDDEN, 'Access denied'),
'BucketAlreadyExists': (
HTTP_CONFLICT, 'The requested bucket name is not available'),
'BucketNotEmpty': (
HTTP_CONFLICT, 'The bucket you tried to delete is not empty'),
'InvalidArgument': (HTTP_BAD_REQUEST, 'Invalid Argument'),
'InvalidBucketName': (
HTTP_BAD_REQUEST, 'The specified bucket is not valid'),
'InvalidURI': (HTTP_BAD_REQUEST, 'Could not parse the specified URI'),
'InvalidDigest': (
HTTP_BAD_REQUEST, 'The Content-MD5 you specified was invalid'),
'BadDigest': (
HTTP_BAD_REQUEST, 'The Content-Length you specified was invalid'),
'EntityTooLarge': (
HTTP_BAD_REQUEST, 'Your proposed upload exceeds the maximum '
'allowed object size.'),
'NoSuchBucket': (
HTTP_NOT_FOUND, 'The specified bucket does not exist'),
'SignatureDoesNotMatch': (
HTTP_FORBIDDEN, 'The calculated request signature does not match '
'your provided one'),
'RequestTimeTooSkewed': (
HTTP_FORBIDDEN, 'The difference between the request time and the '
'current time is too large'),
'NoSuchKey': (
HTTP_NOT_FOUND, 'The resource you requested does not exist'),
'Unsupported': (
HTTP_NOT_IMPLEMENTED, 'The feature you requested is not yet '
'implemented'),
'MissingContentLength': (HTTP_LENGTH_REQUIRED, 'Length Required'),
'ServiceUnavailable': (
HTTP_SERVICE_UNAVAILABLE, 'Please reduce your request rate')}
resp = Response(content_type='text/xml')
resp.status = error_table[code][0]
resp.body = """%s
<Error><Code>%s</Code><Message>%s</Message></Error>
""" % (XML_HEADER, code, error_table[code][1])
return resp
示例11: DELETE
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def DELETE(self, env, start_response):
"""
Handle DELETE Object request
"""
body_iter = self._app_call(env)
status = self._get_status_int()
if status != HTTP_NO_CONTENT:
if status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN):
return get_err_response('AccessDenied')
elif status == HTTP_NOT_FOUND:
return get_err_response('NoSuchKey')
else:
return get_err_response('InvalidURI')
resp = Response()
resp.status = HTTP_NO_CONTENT
return resp
示例12: OPTIONS_base
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def OPTIONS_base(self, req):
"""
Base handler for OPTIONS requests
:param req: swob.Request object
:returns: swob.Response object
"""
headers = {'Allow': ', '.join(self.allowed_methods)}
resp = Response(status=200, request=req,
headers=headers)
req_origin_value = req.headers.get('Origin', None)
if not req_origin_value:
# NOT a CORS request
return resp
# CORS preflight request
try:
container_info = \
self.container_info(self.account_name, self.container_name)
except AttributeError:
container_info = {}
cors = container_info.get('cors', {})
allowed_origins = set()
if cors.get('allow_origin'):
allowed_origins.update(cors['allow_origin'].split(' '))
if self.app.cors_allow_origin:
allowed_origins.update(self.app.cors_allow_origin)
if (req_origin_value not in allowed_origins and
'*' not in allowed_origins) or (
req.headers.get('Access-Control-Request-Method') not in
self.allowed_methods):
resp.status = HTTP_UNAUTHORIZED
return resp # CORS preflight request that isn't valid
headers['access-control-allow-origin'] = req_origin_value
if cors.get('max_age', None) is not None:
headers['access-control-max-age'] = '%d' % cors.get('max_age')
headers['access-control-allow-methods'] = ', '.join(
self.allowed_methods)
if cors.get('allow_headers'):
headers['access-control-allow-headers'] = cors.get('allow_headers')
resp.headers = headers
return resp
示例13: page_main
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def page_main(self, req, storage_url, token):
""" main page container list or object list """
path = urlparse(self.del_prefix(req.url)).path
if len(path.split('/')) <= 2:
path = urlparse(storage_url).path
vrs, acc, cont, obj = split_path(path, 1, 4, True)
path_type = len([i for i in [vrs, acc, cont, obj] if i])
if path_type == 2: # account
return self.page_cont_list(req, storage_url, token)
if path_type == 3: # container
return self.page_obj_list(req, storage_url, token)
if path_type == 4: # object
try:
(obj_status, objct) = get_object(storage_url, token, cont, obj)
except ClientException, e:
resp = Response(charset='utf8')
resp.status = e.http_status
return resp
except err:
pass
示例14: DELETE
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def DELETE(self, env, start_response):
"""
Handle DELETE Bucket request
"""
body_iter = self._app_call(env)
status = self._get_status_int()
if status != HTTP_NO_CONTENT:
if status == HTTP_UNAUTHORIZED:
return get_err_response('AccessDenied')
elif status == HTTP_NOT_FOUND:
return get_err_response('NoSuchBucket')
elif status == HTTP_CONFLICT:
return get_err_response('BucketNotEmpty')
else:
return get_err_response('InvalidURI')
resp = Response()
resp.status = HTTP_NO_CONTENT
return resp
示例15: get_working_response
# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import status [as 别名]
def get_working_response(self, req):
source, node = self._get_source_and_node()
res = None
if source:
res = Response(request=req)
if req.method == "GET" and source.status in (HTTP_OK, HTTP_PARTIAL_CONTENT):
res.app_iter = self._make_app_iter(node, source)
# See NOTE: swift_conn at top of file about this.
res.swift_conn = source.swift_conn
res.status = source.status
update_headers(res, source.getheaders())
if not res.environ:
res.environ = {}
res.environ["swift_x_timestamp"] = source.getheader("x-timestamp")
res.accept_ranges = "bytes"
res.content_length = source.getheader("Content-Length")
if source.getheader("Content-Type"):
res.charset = None
res.content_type = source.getheader("Content-Type")
return res