• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python swob.Response类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: best_response

    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,代码行数:34,代码来源:base.py


示例2: PUT

    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
开发者ID:CiscoSystems,项目名称:swift-plugin-s3,代码行数:60,代码来源:middleware.py


示例3: GET

    def GET(self, request):
        """Handle HTTP GET requests for the Swift Object Server."""
        device, partition, account, container, obj, policy = \
            get_name_and_placement(request, 5, 5, True)
        keep_cache = self.keep_cache_private or (
            'X-Auth-Token' not in request.headers and
            'X-Storage-Token' not in request.headers)

        cloud_container_info = request.headers.get('X-Storage-Container')
        cloud_container = cloud_container_info.strip().split('/')
        obj_iter = get_file(cloud_container[0], cloud_container[1],
            obj)
        conditional_etag = md5()

        if None == obj_iter:
            return HTTPNotFound(request=request)

        response = Response(
                app_iter=obj_iter,
                request=request, conditional_response=True,
                conditional_etag=conditional_etag)
        response.headers['Content-Type'] = 'application/octet-stream'
        #response.etag = metadata['ETag']
        #response.last_modified = math.ceil(float(file_x_ts))
        #response.content_length = obj_size

        #response.headers['X-Timestamp'] = file_x_ts.normal
        #response.headers['X-Backend-Timestamp'] = file_x_ts.internal
        resp = request.get_response(response)
        return resp
开发者ID:kun--hust,项目名称:sdscloud,代码行数:30,代码来源:server.py


示例4: best_response

    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,代码行数:28,代码来源:base.py


示例5: page_obj_list

 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
开发者ID:famao,项目名称:Taylor,代码行数:27,代码来源:taylor.py


示例6: zip_get_content_response

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,代码行数:34,代码来源:get_as.py


示例7: OPTIONS

    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
开发者ID:HoO-Group,项目名称:swift,代码行数:59,代码来源:base.py


示例8: __call__

 def __call__(self, env, start_response):
     self.req = Request(env)
     resp = Response(request=self.req, body=b'FAKE APP',
                     headers=self.headers)
     # like webob, middlewares in the pipeline may rewrite
     # location header from relative to absolute
     resp.location = resp.absolute_location()
     return resp(env, start_response)
开发者ID:jgmerritt,项目名称:swift,代码行数:8,代码来源:test_gatekeeper.py


示例9: part_with_attachment

 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,代码行数:8,代码来源:get_as.py


示例10: get_err_response

 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,代码行数:9,代码来源:middleware.py


示例11: HEAD

 def HEAD(self, request):
     """Handle HTTP HEAD requests for the Swift Object Server."""
     device, partition, account, container, obj, policy_idx = get_name_and_placement(request, 5, 5, True)
     try:
         disk_file = self.get_diskfile(device, partition, account, container, obj, policy_idx=policy_idx)
     except DiskFileDeviceUnavailable:
         return HTTPInsufficientStorage(drive=device, request=request)
     try:
         metadata = disk_file.read_metadata()
     except DiskFileXattrNotSupported:
         return HTTPInsufficientStorage(drive=device, request=request)
     except (DiskFileNotExist, DiskFileQuarantined) as e:
         headers = {}
         if hasattr(e, "timestamp"):
             headers["X-Backend-Timestamp"] = e.timestamp.internal
         return HTTPNotFound(request=request, headers=headers, conditional_response=True)
     response = Response(request=request, conditional_response=True)
     response.headers["Content-Type"] = metadata.get("Content-Type", "application/octet-stream")
     for key, value in metadata.iteritems():
         if is_sys_or_user_meta("object", key) or key.lower() in self.allowed_headers:
             response.headers[key] = value
     response.etag = metadata["ETag"]
     ts = Timestamp(metadata["X-Timestamp"])
     response.last_modified = math.ceil(float(ts))
     # Needed for container sync feature
     response.headers["X-Timestamp"] = ts.normal
     response.headers["X-Backend-Timestamp"] = ts.internal
     response.content_length = int(metadata["Content-Length"])
     try:
         response.content_encoding = metadata["Content-Encoding"]
     except KeyError:
         pass
     return response
开发者ID:steveruckdashel,项目名称:swift,代码行数:33,代码来源:server.py


示例12: OPTIONS

    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
开发者ID:GoodDingo,项目名称:openstack-swift,代码行数:54,代码来源:base.py


示例13: get_err_response

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,代码行数:54,代码来源:utils.py


示例14: GET

    def GET(self, request):
        """Handle HTTP GET requests for the Swift Object Server."""
        device, partition, account, container, obj, policy = \
            get_name_and_placement(request, 5, 5, True)
	print 'request',request
	print 'device, partition, account, container,obj, policy', device,partition,account,container,obj,policy
        keep_cache = self.keep_cache_private or (
            'X-Auth-Token' not in request.headers and
            'X-Storage-Token' not in request.headers)
        try:
            disk_file = self.get_diskfile(
                device, partition, account, container, obj,
                policy=policy)
	    print 'disk_file',disk_file 
        except DiskFileDeviceUnavailable:
            return HTTPInsufficientStorage(drive=device, request=request)
        try:
            with disk_file.open():
                metadata = disk_file.get_metadata()
                obj_size = int(metadata['Content-Length'])
                file_x_ts = Timestamp(metadata['X-Timestamp'])
                keep_cache = (self.keep_cache_private or
                              ('X-Auth-Token' not in request.headers and
                               'X-Storage-Token' not in request.headers))
                conditional_etag = None
                if 'X-Backend-Etag-Is-At' in request.headers:
                    conditional_etag = metadata.get(
                        request.headers['X-Backend-Etag-Is-At'])
                response = Response(
                    app_iter=disk_file.reader(keep_cache=keep_cache),
                    request=request, conditional_response=True,
                    conditional_etag=conditional_etag)
                response.headers['Content-Type'] = metadata.get(
                    'Content-Type', 'application/octet-stream')
                for key, value in metadata.iteritems():
                    if is_sys_or_user_meta('object', key) or \
                            key.lower() in self.allowed_headers:
                        response.headers[key] = value
                response.etag = metadata['ETag']
                response.last_modified = math.ceil(float(file_x_ts))
                response.content_length = obj_size
                try:
                    response.content_encoding = metadata[
                        'Content-Encoding']
                except KeyError:
                    pass
                response.headers['X-Timestamp'] = file_x_ts.normal
                response.headers['X-Backend-Timestamp'] = file_x_ts.internal
                resp = request.get_response(response)
        except DiskFileXattrNotSupported:
            return HTTPInsufficientStorage(drive=device, request=request)
        except (DiskFileNotExist, DiskFileQuarantined) as e:
            headers = {}
            if hasattr(e, 'timestamp'):
                headers['X-Backend-Timestamp'] = e.timestamp.internal
            resp = HTTPNotFound(request=request, headers=headers,
                                conditional_response=True)
	print 'resp',resp
	return resp
开发者ID:jannatunnoor,项目名称:test_swift,代码行数:59,代码来源:server.py


示例15: HEAD

    def HEAD(self, request):
        """Handle HTTP HEAD requests for the Swift on File object server"""
        device, partition, account, container, obj, policy = \
            get_name_and_placement(request, 5, 5, True)

        # Get DiskFile
        try:
            disk_file = self.get_diskfile(device, partition, account, container,
                                          obj, policy=policy)

        except DiskFileDeviceUnavailable:
            return HTTPInsufficientStorage(drive=device, request=request)

        # Read DiskFile metadata
        try:
            disk_file.open()
            metadata = disk_file.get_metadata()
        except (DiskFileNotExist, DiskFileQuarantined) as e:
            headers = {}
            if hasattr(e, 'timestamp'):
                headers['X-Backend-Timestamp'] = e.timestamp.internal
            return HTTPNotFound(request=request, headers=headers,
                                conditional_respose=True)

        # Create and populate our response
        response = Response(request=request, conditional_response=True)
        response.headers['Content-Type'] = \
            metadata.get('Content-Type', 'application/octet-stream')
        for key, value in metadata.iteritems():
            if is_sys_or_user_meta('object', key) or key.lower() in \
                    self.allowed_headers:
                response.headers[key] = value
        response.etag = metadata['ETag']
        ts = Timestamp(metadata['X-Timestamp'])
        response.last_modified = math.ceil(float(ts))
        # Needed for container sync feature
        response.headers['X-Timestamp'] = ts.normal
        response.headers['X-Backend-Timestamp'] = ts.internal
        response.content_length = int(metadata['Content-Length'])
        try:
            response.content_encoding = metadata['Content-Encoding']
        except KeyError:
            pass

        # (HPSS) Inject HPSS xattr metadata into headers
        want_hpss_metadata = request.headers.get('X-HPSS-Get-Metadata',
                                                 False)
        if config_true_value(want_hpss_metadata):
            try:
                hpss_headers = disk_file.read_hpss_system_metadata()
                response.headers.update(hpss_headers)
            except SwiftOnFileSystemIOError:
                return HTTPServiceUnavailable(request=request)

        if 'X-Object-Sysmeta-Update-Container' in response.headers:
            self._sof_container_update(request, response)
            response.headers.pop('X-Object-Sysmeta-Update-Container')

        return response
开发者ID:hpss-collaboration,项目名称:swiftonhpss,代码行数:59,代码来源:server.py


示例16: test_add_acls_impossible_cases

    def test_add_acls_impossible_cases(self):
        # For test coverage: verify that defensive coding does defend, in cases
        # that shouldn't arise naturally

        # add_acls should do nothing if REQUEST_METHOD isn't HEAD/GET/PUT/POST
        resp = Response()
        controller = proxy_server.AccountController(self.app, 'a')
        resp.environ['PATH_INFO'] = '/a'
        resp.environ['REQUEST_METHOD'] = 'OPTIONS'
        controller.add_acls_from_sys_metadata(resp)
        self.assertEqual(1, len(resp.headers))  # we always get Content-Type
        self.assertEqual(2, len(resp.environ))
开发者ID:BjoernT,项目名称:swift,代码行数:12,代码来源:test_account.py


示例17: HEAD

 def HEAD(self, request):
     """Handle HTTP HEAD requests for the Swift Object Server."""
     device, partition, account, container, obj = \
         split_and_validate_path(request, 5, 5, True)
     try:
         disk_file = self._diskfile(device, partition, account, container,
                                    obj)
     except DiskFileDeviceUnavailable:
         return HTTPInsufficientStorage(drive=device, request=request)
     with disk_file.open():
         if disk_file.is_deleted() or disk_file.is_expired():
             return HTTPNotFound(request=request)
         try:
             file_size = disk_file.get_data_file_size()
         except (DiskFileError, DiskFileNotExist):
             disk_file.quarantine()
             return HTTPNotFound(request=request)
         metadata = disk_file.get_metadata()
     response = Response(request=request, conditional_response=True)
     response.headers['Content-Type'] = metadata.get(
         'Content-Type', 'application/octet-stream')
     for key, value in metadata.iteritems():
         if key.lower().startswith('x-object-meta-') or \
                 key.lower() in self.allowed_headers:
             response.headers[key] = value
     response.etag = metadata['ETag']
     response.last_modified = float(metadata['X-Timestamp'])
     # Needed for container sync feature
     response.headers['X-Timestamp'] = metadata['X-Timestamp']
     response.content_length = file_size
     if 'Content-Encoding' in metadata:
         response.content_encoding = metadata['Content-Encoding']
     return response
开发者ID:mawentao007,项目名称:swift,代码行数:33,代码来源:server.py


示例18: HEAD

    def HEAD(self, request):
        """Handle HTTP HEAD requests for the Swift Object Server."""
        device, partition, account, container, obj = self._parse_path(request)

        try:
            disk_file = self._diskfile(device, partition, account, container, obj)
        except DiskFileDeviceUnavailable:
            return HTTPInsufficientStorage(drive=device, request=request)
        if disk_file.is_deleted() or disk_file.is_expired():
            return HTTPNotFound(request=request)
        try:
            file_size = disk_file.get_data_file_size()
        except (DiskFileError, DiskFileNotExist):
            disk_file.quarantine()
            return HTTPNotFound(request=request)
        response = Response(request=request, conditional_response=True)
        response.headers["Content-Type"] = disk_file.metadata.get("Content-Type", "application/octet-stream")
        for key, value in disk_file.metadata.iteritems():
            if key.lower().startswith("x-object-meta-") or key.lower() in self.allowed_headers:
                response.headers[key] = value
        response.etag = disk_file.metadata["ETag"]
        response.last_modified = float(disk_file.metadata["X-Timestamp"])
        # Needed for container sync feature
        response.headers["X-Timestamp"] = disk_file.metadata["X-Timestamp"]
        response.content_length = file_size
        if "Content-Encoding" in disk_file.metadata:
            response.content_encoding = disk_file.metadata["Content-Encoding"]
        return response
开发者ID:navidshaikh,项目名称:swift,代码行数:28,代码来源:server.py


示例19: make_object_response

    def make_object_response(self, req, metadata, stream=None):
        conditional_etag = None
        if 'X-Backend-Etag-Is-At' in req.headers:
            conditional_etag = metadata.get(
                req.headers['X-Backend-Etag-Is-At'])

        resp = Response(request=req, conditional_response=True,
                        conditional_etag=conditional_etag)

        resp.headers['Content-Type'] = metadata.get(
            'mime-type', 'application/octet-stream')
        for k, v in metadata.iteritems():
            if k.startswith("user."):
                meta = k[5:]
                if is_sys_or_user_meta('object', meta) or \
                                meta.lower() in self.allowed_headers:
                    resp.headers[meta] = v
        resp.etag = metadata['hash'].lower()
        ts = Timestamp(metadata['ctime'])
        resp.last_modified = math.ceil(float(ts))
        if stream:
            resp.app_iter = stream
        resp.content_length = int(metadata['length'])
        try:
            resp.content_encoding = metadata['encoding']
        except KeyError:
            pass
        return resp
开发者ID:GuillaumeDelaporte,项目名称:oio-swift,代码行数:28,代码来源:obj.py


示例20: HEAD

 def HEAD(self, request):
     """Handle HTTP HEAD requests for the Swift Object Server."""
     device, partition, account, container, obj = \
         split_and_validate_path(request, 5, 5, True)
     try:
         disk_file = self.get_diskfile(
             device, partition, account, container, obj)
     except DiskFileDeviceUnavailable:
         return HTTPInsufficientStorage(drive=device, request=request)
     try:
         metadata = disk_file.read_metadata()
     except (DiskFileNotExist, DiskFileQuarantined):
         return HTTPNotFound(request=request, conditional_response=True)
     response = Response(request=request, conditional_response=True)
     response.headers['Content-Type'] = metadata.get(
         'Content-Type', 'application/octet-stream')
     for key, value in metadata.iteritems():
         if is_user_meta('object', key) or \
                 key.lower() in self.allowed_headers:
             response.headers[key] = value
     response.etag = metadata['ETag']
     ts = metadata['X-Timestamp']
     response.last_modified = math.ceil(float(ts))
     # Needed for container sync feature
     response.headers['X-Timestamp'] = ts
     response.content_length = int(metadata['Content-Length'])
     try:
         response.content_encoding = metadata['Content-Encoding']
     except KeyError:
         pass
     return response
开发者ID:HoO-Group,项目名称:swift,代码行数:31,代码来源:server.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.audit_location_generator函数代码示例发布时间:2022-05-27
下一篇:
Python swob.Request类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap