当前位置: 首页>>代码示例>>Python>>正文


Python Response.body方法代码示例

本文整理汇总了Python中swift.common.swob.Response.body方法的典型用法代码示例。如果您正苦于以下问题:Python Response.body方法的具体用法?Python Response.body怎么用?Python Response.body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在swift.common.swob.Response的用法示例。


在下文中一共展示了Response.body方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_listing

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
 def create_listing(self, req, out_content_type, info, metadata,
                    container_list, container):
     list_meta = get_param(req, 'list_meta', 'f').lower() in TRUE_VALUES
     resp_headers = {
         'X-Container-Object-Count': info['object_count'],
         'X-Container-Bytes-Used': info['bytes_used'],
         'X-Timestamp': info['created_at'],
         'X-PUT-Timestamp': info['put_timestamp'],
     }
     for key, (value, timestamp) in metadata.iteritems():
         if value and (key.lower() in self.save_headers or
                       is_sys_or_user_meta('container', key)):
             resp_headers[key] = value
     ret = Response(request=req, headers=resp_headers,
                    content_type=out_content_type, charset='utf-8')
     if out_content_type == 'application/json':
         ret.body = json.dumps([self.update_data_record(record, list_meta)
                                for record in container_list])
     elif out_content_type.endswith('/xml'):
         doc = Element('container', name=container.decode('utf-8'))
         for obj in container_list:
             record = self.update_data_record(obj, list_meta)
             if 'subdir' in record:
                 name = record['subdir'].decode('utf-8')
                 sub = SubElement(doc, 'subdir', name=name)
                 SubElement(sub, 'name').text = name
             else:
                 obj_element = SubElement(doc, 'object')
                 for field in ["name", "hash", "bytes", "content_type",
                               "last_modified"]:
                     SubElement(obj_element, field).text = str(
                         record.pop(field)).decode('utf-8')
                 for field in sorted(record):
                     if list_meta and field == 'metadata':
                         meta = SubElement(obj_element, field)
                         for k, v in record[field].iteritems():
                             SubElement(meta, k).text = str(
                                 v.decode('utf-8'))
                     else:
                         SubElement(obj_element, field).text = str(
                             record[field]).decode('utf-8')
         ret.body = tostring(doc, encoding='UTF-8').replace(
             "<?xml version='1.0' encoding='UTF-8'?>",
             '<?xml version="1.0" encoding="UTF-8"?>', 1)
     else:
         if not container_list:
             return HTTPNoContent(request=req, headers=resp_headers)
         ret.body = '\n'.join(rec[0] for rec in container_list) + '\n'
     return ret
开发者ID:pkit,项目名称:zwift,代码行数:51,代码来源:server.py

示例2: zip_get_content_response

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
def zip_get_content_response(fp, files, boundary=_boundary):
    def part_with_attachment(fn):
        part = Response(headers={
            'Content-Type': 'application/octet-stream',
            'Content-Disposition': 'attachment; filename=%s' %
            fn.encode('utf-8'),
            })
        part.body = zip_file.read(fn)
        return part

    with zipfile.ZipFile(fp) as zip_file:
        try:
            total_size = sum(zip_file.getinfo(fn).file_size for fn in files)
        except KeyError:
            raise HTTPNotFound(body='File not found in the zip\r\n')

        if total_size > MAX_CONTENT_SIZE:
            raise HTTPRequestEntityTooLarge()

        if len(files) == 1:
            resp = part_with_attachment(files[0])
        else:
            resp = Response(
                content_type='multipart/mixed; boundary=%s' % boundary)
            body = io.BytesIO()
            for fn in files:
                part_resp = part_with_attachment(fn)
                body.write('\r\n--%s\r\n' % boundary)
                body.write(dump_response(part_resp))

            body.write('\r\n--%s--\r\n' % boundary)
            resp.body = body.getvalue()

    return resp
开发者ID:s4g,项目名称:swift,代码行数:36,代码来源:get_as.py

示例3: best_response

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [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
开发者ID:WIZARD-CXY,项目名称:swift,代码行数:30,代码来源:base.py

示例4: best_response

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [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
开发者ID:sa4250mnpo70,项目名称:swift,代码行数:36,代码来源:base.py

示例5: part_with_attachment

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
 def part_with_attachment(fn):
     part = Response(headers={
         'Content-Type': 'application/octet-stream',
         'Content-Disposition': 'attachment; filename=%s' %
         fn.encode('utf-8'),
         })
     part.body = zip_file.read(fn)
     return part
开发者ID:s4g,项目名称:swift,代码行数:10,代码来源:get_as.py

示例6: get_err_response

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [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
开发者ID:synhershko,项目名称:swift-middleware-grok,代码行数:11,代码来源:middleware.py

示例7: get_err_response

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [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
开发者ID:Nexenta,项目名称:swift3,代码行数:56,代码来源:utils.py

示例8: create_listing

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
 def create_listing(self, req, out_content_type, resp_headers,
                    metadata, result_list, container):
     container_list = result_list['objects']
     for p in result_list.get('prefixes', []):
         record = {'name': p,
                   'subdir': True}
         container_list.append(record)
     for (k, v) in metadata.iteritems():
         if v and (k.lower() in self.pass_through_headers or
                       is_sys_or_user_meta('container', k)):
             resp_headers[k] = v
     ret = Response(request=req, headers=resp_headers,
                    content_type=out_content_type, charset='utf-8')
     if out_content_type == 'application/json':
         ret.body = json.dumps([self.update_data_record(record)
                                for record in container_list])
     elif out_content_type.endswith('/xml'):
         doc = Element('container', name=container.decode('utf-8'))
         for obj in container_list:
             record = self.update_data_record(obj)
             if 'subdir' in record:
                 name = record['subdir'].decode('utf-8')
                 sub = SubElement(doc, 'subdir', name=name)
                 SubElement(sub, 'name').text = name
             else:
                 obj_element = SubElement(doc, 'object')
                 for field in ["name", "hash", "bytes", "content_type",
                               "last_modified"]:
                     SubElement(obj_element, field).text = str(
                         record.pop(field)).decode('utf-8')
                 for field in sorted(record):
                     SubElement(obj_element, field).text = str(
                         record[field]).decode('utf-8')
         ret.body = tostring(doc, encoding='UTF-8').replace(
             "<?xml version='1.0' encoding='UTF-8'?>",
             '<?xml version="1.0" encoding="UTF-8"?>', 1)
     else:
         if not container_list:
             return HTTPNoContent(request=req, headers=resp_headers)
         ret.body = '\n'.join(rec['name'] for rec in container_list) + '\n'
     return ret
开发者ID:GuillaumeDelaporte,项目名称:oio-swift,代码行数:43,代码来源:container.py

示例9: create_listing

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
 def create_listing(self, req, out_content_type, info, resp_headers,
                    metadata, container_list, container):
     for key, (value, timestamp) in metadata.items():
         if value and (key.lower() in self.save_headers or
                       is_sys_or_user_meta('container', key)):
             resp_headers[key] = value
     ret = Response(request=req, headers=resp_headers,
                    content_type=out_content_type, charset='utf-8')
     if out_content_type == 'application/json':
         ret.body = json.dumps([self.update_data_record(record)
                                for record in container_list])
     elif out_content_type.endswith('/xml'):
         doc = Element('container', name=container.decode('utf-8'))
         for obj in container_list:
             record = self.update_data_record(obj)
             if 'subdir' in record:
                 name = record['subdir'].decode('utf-8')
                 sub = SubElement(doc, 'subdir', name=name)
                 SubElement(sub, 'name').text = name
             else:
                 obj_element = SubElement(doc, 'object')
                 for field in ["name", "hash", "bytes", "content_type",
                               "last_modified"]:
                     SubElement(obj_element, field).text = str(
                         record.pop(field)).decode('utf-8')
                 for field in sorted(record):
                     SubElement(obj_element, field).text = str(
                         record[field]).decode('utf-8')
         ret.body = tostring(doc, encoding='UTF-8').replace(
             "<?xml version='1.0' encoding='UTF-8'?>",
             '<?xml version="1.0" encoding="UTF-8"?>', 1)
     else:
         if not container_list:
             return HTTPNoContent(request=req, headers=resp_headers)
         ret.body = '\n'.join(rec[0] for rec in container_list) + '\n'
     ret.last_modified = math.ceil(float(resp_headers['X-PUT-Timestamp']))
     return ret
开发者ID:bebule,项目名称:swift,代码行数:39,代码来源:server.py

示例10: _deny_request

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [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
开发者ID:,项目名称:,代码行数:17,代码来源:

示例11: get_err_response

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [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
开发者ID:swiftstack,项目名称:swift3,代码行数:49,代码来源:middleware.py

示例12: GET

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
    def GET(self, req):
        """
        Load ring data from .gz files.
        """

        self._reload()
        ring_info = self._to_dict()
        gz_file_to_ring_info = json.dumps(ring_info, sort_keys=True)
        ring_info_json_md5 = self._ringinfo_md5(gz_file_to_ring_info)

        resp = Response(request=req)
        resp.etag = ring_info_json_md5
        resp.content_length = len(gz_file_to_ring_info)
        resp.body = gz_file_to_ring_info
        resp.status_init = 200
        resp.content_type = 'application/json; charset=UTF-8'
        return resp
开发者ID:HeyManLeader,项目名称:OpenStack-Swift,代码行数:19,代码来源:gziptojson.py

示例13: get_err_response

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [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"),
        "NoSuchObject": (HTTP_NOT_FOUND, "The specified object does not exist"),
        "NoSuchBucket": (HTTP_NOT_FOUND, "The specified bucket does not exist"),
        "NoSuchUpload": (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 = (
        '<?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
开发者ID:pyKun,项目名称:s3multi,代码行数:42,代码来源:middleware.py

示例14: and

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
 resp_headers = {
     'X-Container-Object-Count': info['object_count'],
     'X-Container-Bytes-Used': info['bytes_used'],
     'X-Timestamp': info['created_at'],
     'X-PUT-Timestamp': info['put_timestamp'],
 }
 for key, (value, timestamp) in broker.metadata.iteritems():
     if value and (key.lower() in self.save_headers or
                   key.lower().startswith('x-container-meta-')):
         resp_headers[key] = value
 ret = Response(request=req, headers=resp_headers,
                content_type=out_content_type, charset='utf-8')
 container_list = broker.list_objects_iter(limit, marker, end_marker,
                                           prefix, delimiter, path)
 if out_content_type == 'application/json':
     ret.body = json.dumps([self.update_data_record(record)
                            for record in container_list])
 elif out_content_type.endswith('/xml'):
     doc = Element('container', name=container.decode('utf-8'))
     for obj in container_list:
         record = self.update_data_record(obj)
         if 'subdir' in record:
             name = record['subdir'].decode('utf-8')
             sub = SubElement(doc, 'subdir', name=name)
             SubElement(sub, 'name').text = name
         else:
             obj_element = SubElement(doc, 'object')
             for field in ["name", "hash", "bytes", "content_type",
                           "last_modified"]:
                 SubElement(obj_element, field).text = str(
                     record.pop(field)).decode('utf-8')
             for field in sorted(record.keys()):
开发者ID:GitFloki,项目名称:Shake,代码行数:34,代码来源:server.py

示例15: GET

# 需要导入模块: from swift.common.swob import Response [as 别名]
# 或者: from swift.common.swob.Response import body [as 别名]
 def GET(self, req):
     """Handle HTTP GET request."""
     drive, part, account, container, obj = split_and_validate_path(
         req, 4, 5, True)
     path = get_param(req, 'path')
     prefix = get_param(req, 'prefix')
     delimiter = get_param(req, 'delimiter')
     if delimiter and (len(delimiter) > 1 or ord(delimiter) > 254):
         # delimiters can be made more flexible later
         return HTTPPreconditionFailed(body='Bad delimiter')
     marker = get_param(req, 'marker', '')
     end_marker = get_param(req, 'end_marker')
     limit = constraints.CONTAINER_LISTING_LIMIT
     given_limit = get_param(req, 'limit')
     if given_limit and given_limit.isdigit():
         limit = int(given_limit)
         if limit > constraints.CONTAINER_LISTING_LIMIT:
             return HTTPPreconditionFailed(
                 request=req,
                 body='Maximum limit is %d'
                 % constraints.CONTAINER_LISTING_LIMIT)
     out_content_type = get_listing_content_type(req)
     if self.mount_check and not check_mount(self.root, drive):
         return HTTPInsufficientStorage(drive=drive, request=req)
     broker = self._get_container_broker(drive, part, account, container,
                                         pending_timeout=0.1,
                                         stale_reads_ok=True)
     if broker.is_deleted():
         return HTTPNotFound(request=req)
     info = broker.get_info()
     resp_headers = {
         'X-Container-Object-Count': info['object_count'],
         'X-Container-Bytes-Used': info['bytes_used'],
         'X-Timestamp': info['created_at'],
         'X-PUT-Timestamp': info['put_timestamp'],
     }
     for key, (value, timestamp) in broker.metadata.iteritems():
         if value and (key.lower() in self.save_headers or
                       is_sys_or_user_meta('container', key)):
             resp_headers[key] = value
     ret = Response(request=req, headers=resp_headers,
                    content_type=out_content_type, charset='utf-8')
     container_list = broker.list_objects_iter(limit, marker, end_marker,
                                               prefix, delimiter, path)
     if out_content_type == 'application/json':
         ret.body = json.dumps([self.update_data_record(record)
                                for record in container_list])
     elif out_content_type.endswith('/xml'):
         doc = Element('container', name=container.decode('utf-8'))
         for obj in container_list:
             record = self.update_data_record(obj)
             if 'subdir' in record:
                 name = record['subdir'].decode('utf-8')
                 sub = SubElement(doc, 'subdir', name=name)
                 SubElement(sub, 'name').text = name
             else:
                 obj_element = SubElement(doc, 'object')
                 for field in ["name", "hash", "bytes", "content_type",
                               "last_modified"]:
                     SubElement(obj_element, field).text = str(
                         record.pop(field)).decode('utf-8')
                 for field in sorted(record):
                     SubElement(obj_element, field).text = str(
                         record[field]).decode('utf-8')
         ret.body = tostring(doc, encoding='UTF-8').replace(
             "<?xml version='1.0' encoding='UTF-8'?>",
             '<?xml version="1.0" encoding="UTF-8"?>', 1)
     else:
         if not container_list:
             return HTTPNoContent(request=req, headers=resp_headers)
         ret.body = '\n'.join(rec[0] for rec in container_list) + '\n'
     return ret
开发者ID:HoO-Group,项目名称:swift,代码行数:74,代码来源:server.py


注:本文中的swift.common.swob.Response.body方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。