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

Python constraints.check_utf8函数代码示例

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

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



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

示例1: validate_metadata

    def validate_metadata(metadata):
        """
        Validates that metadata falls within acceptable limits.

        :param metadata: to be validated
        :raises HTTPBadRequest: if MAX_META_COUNT or MAX_META_OVERALL_SIZE
                 is exceeded, or if metadata contains non-UTF-8 data
        """
        meta_count = 0
        meta_size = 0
        for key, (value, timestamp) in metadata.items():
            if key and not isinstance(key, six.text_type):
                if not check_utf8(key):
                    raise HTTPBadRequest('Metadata must be valid UTF-8')
                # Promote to a natural string for the checks below
                if six.PY3:
                    key = key.decode('utf8')
            if value and not isinstance(value, six.text_type):
                if not check_utf8(value):
                    raise HTTPBadRequest('Metadata must be valid UTF-8')
            key = key.lower()
            if value and key.startswith(('x-account-meta-',
                                         'x-container-meta-')):
                prefix = 'x-account-meta-'
                if key.startswith('x-container-meta-'):
                    prefix = 'x-container-meta-'
                key = key[len(prefix):]
                meta_count = meta_count + 1
                meta_size = meta_size + len(key) + len(value)
        if meta_count > MAX_META_COUNT:
            raise HTTPBadRequest('Too many metadata items; max %d'
                                 % MAX_META_COUNT)
        if meta_size > MAX_META_OVERALL_SIZE:
            raise HTTPBadRequest('Total metadata too large; max %d'
                                 % MAX_META_OVERALL_SIZE)
开发者ID:jgmerritt,项目名称:swift,代码行数:35,代码来源:db.py


示例2: validate_metadata

    def validate_metadata(metadata):
        """
        Validates that metadata falls within acceptable limits.

        :param metadata: to be validated
        :raises: HTTPBadRequest if MAX_META_COUNT or MAX_META_OVERALL_SIZE
                 is exceeded, or if metadata contains non-UTF-8 data
        """
        meta_count = 0
        meta_size = 0
        for key, (value, timestamp) in metadata.items():
            key = key.lower()
            if value != '' and (key.startswith('x-account-meta') or
                                key.startswith('x-container-meta')):
                prefix = 'x-account-meta-'
                if key.startswith('x-container-meta-'):
                    prefix = 'x-container-meta-'
                key = key[len(prefix):]
                meta_count = meta_count + 1
                meta_size = meta_size + len(key) + len(value)
            bad_key = key and not check_utf8(key)
            bad_value = value and not check_utf8(value)
            if bad_key or bad_value:
                raise HTTPBadRequest('Metadata must be valid UTF-8')
        if meta_count > MAX_META_COUNT:
            raise HTTPBadRequest('Too many metadata items; max %d'
                                 % MAX_META_COUNT)
        if meta_size > MAX_META_OVERALL_SIZE:
            raise HTTPBadRequest('Total metadata too large; max %d'
                                 % MAX_META_OVERALL_SIZE)
开发者ID:bebule,项目名称:swift,代码行数:30,代码来源:db.py


示例3: PUT

 def PUT(self, req):
     """Handle HTTP PUT request."""
     try:
         drive, part, account, container = split_path(unquote(req.path),
                                                      3, 4)
         if (account and not check_utf8(account)) or \
             (container and not check_utf8(container)):
             raise ValueError('NULL characters not allowed in names')
     except ValueError, err:
         return HTTPBadRequest(body=str(err), content_type='text/plain',
                               request=req)
开发者ID:Gaurav-Gangalwar,项目名称:UFO,代码行数:11,代码来源:server.py


示例4: test_check_utf8

    def test_check_utf8(self):
        unicode_sample = u"\uc77c\uc601"
        valid_utf8_str = unicode_sample.encode("utf-8")
        invalid_utf8_str = unicode_sample.encode("utf-8")[::-1]
        unicode_with_null = u"abc\u0000def"
        utf8_with_null = unicode_with_null.encode("utf-8")

        for false_argument in [None, "", invalid_utf8_str, unicode_with_null, utf8_with_null]:
            self.assertFalse(constraints.check_utf8(false_argument))

        for true_argument in ["this is ascii and utf-8, too", unicode_sample, valid_utf8_str]:
            self.assertTrue(constraints.check_utf8(true_argument))
开发者ID:heemanshu,项目名称:swift_liberty,代码行数:12,代码来源:test_constraints.py


示例5: test_check_utf8

    def test_check_utf8(self):
        unicode_sample = u'\uc77c\uc601'
        valid_utf8_str = unicode_sample.encode('utf-8')
        invalid_utf8_str = unicode_sample.encode('utf-8')[::-1]

        for false_argument in [None,
                               '',
                               invalid_utf8_str,
                               ]:
            self.assertFalse(constraints.check_utf8(false_argument))

        for true_argument in ['this is ascii and utf-8, too',
                              unicode_sample,
                              valid_utf8_str]:
            self.assertTrue(constraints.check_utf8(true_argument))
开发者ID:VictorLowther,项目名称:swift,代码行数:15,代码来源:test_constraints.py


示例6: __call__

 def __call__(self, env, start_response):
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get("x-trans-id", None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body="Invalid UTF8 or contains NULL")
     else:
         try:
             # disallow methods which are not publicly accessible
             try:
                 if req.method not in self.allowed_methods:
                     raise AttributeError("Not allowed method.")
             except AttributeError:
                 res = HTTPMethodNotAllowed()
             else:
                 method = getattr(self, req.method)
                 res = method(req)
         except HTTPException as error_response:
             res = error_response
         except (Exception, Timeout):
             self.logger.exception(
                 _("ERROR __call__ error with %(method)s" " %(path)s "), {"method": req.method, "path": req.path}
             )
             res = HTTPInternalServerError(body=traceback.format_exc())
     if self.log_requests:
         trans_time = time.time() - start_time
         additional_info = ""
         if res.headers.get("x-container-timestamp") is not None:
             additional_info += "x-container-timestamp: %s" % res.headers["x-container-timestamp"]
         log_msg = get_log_line(req, res, trans_time, additional_info)
         if req.method.upper() == "REPLICATE":
             self.logger.debug(log_msg)
         else:
             self.logger.info(log_msg)
     return res(env, start_response)
开发者ID:steveruckdashel,项目名称:swift,代码行数:35,代码来源:server.py


示例7: handle_request

    def handle_request(self, req):

        try:
            self.logger.set_statsd_prefix('proxy-server')
            if req.content_length and req.content_length < 0:
                return jresponse('-1','Invalid Content-Length',req,400)
                
            try:
                if not check_utf8(req.path_info):
                    
                    return jresponse('-1','Invalid UTF8',req,412)
            except UnicodeError:
                return jresponse('-1','Invalid UTF8',req,412)
                
            
            try:
                controller, path_parts = self.get_controller(req)
                p = req.path_info
                if isinstance(p, unicode):
                    p = p.encode('utf-8')
            except ValueError:
                return jresponse('-1','not found',req,404)
            if not controller:
                return jresponse('-1','Bad URL',req,412)
            
            if self.deny_host_headers and \
                    req.host.split(':')[0] in self.deny_host_headers:
                return HTTPForbidden(request=req, body='Invalid host header')
            if not check_path_parts(path_parts):
                return HTTPForbidden(request=req, body='Invalid path_parts header')
            
            self.logger.set_statsd_prefix('proxy-server.' +
                                          controller.server_type.lower())
            
            controller = controller(self, **path_parts)
            if 'swift.trans_id' not in req.environ:
                # if this wasn't set by an earlier middleware, set it now
                trans_id = 'tx' + uuid.uuid4().hex
                req.environ['swift.trans_id'] = trans_id
                self.logger.txn_id = trans_id
            req.headers['x-trans-id'] = req.environ['swift.trans_id']
            controller.trans_id = req.environ['swift.trans_id']
            self.logger.client_ip = get_remote_client(req)
            
            try:
                if req.GET.get('op'):
                    req.method = req.GET.get('op')
                    
                handler = getattr(controller, req.method)
                getattr(handler, 'publicly_accessible')
            except AttributeError:
                return HTTPMethodNotAllowed(request=req)
            if path_parts['version']:
                req.path_info_pop()
    
            req.environ['swift.orig_req_method'] = req.method
            return handler(req)
        except (Exception, Timeout):
            self.logger.exception(_('ERROR Unhandled exception in request'))
            return jresponse('-1','ServerERROR',req,500)
开发者ID:sun3shines,项目名称:swift-1.7.4,代码行数:60,代码来源:server.py


示例8: __call__

 def __call__(self, env, start_response):
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get('x-trans-id', None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body='Invalid UTF8')
     else:
         try:
             if hasattr(self, req.method):
                 res = getattr(self, req.method)(req)
             else:
                 res = HTTPMethodNotAllowed()
         except (Exception, Timeout):
             self.logger.exception(_('ERROR __call__ error with %(method)s'
                 ' %(path)s '), {'method': req.method, 'path': req.path})
             res = HTTPInternalServerError(body=traceback.format_exc())
     trans_time = '%.4f' % (time.time() - start_time)
     additional_info = ''
     if res.headers.get('x-container-timestamp') is not None:
         additional_info += 'x-container-timestamp: %s' % \
             res.headers['x-container-timestamp']
     log_message = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %s "%s"' % (
         req.remote_addr,
         time.strftime('%d/%b/%Y:%H:%M:%S +0000', time.gmtime()),
         req.method, req.path,
         res.status.split()[0], res.content_length or '-',
         req.headers.get('x-trans-id', '-'),
         req.referer or '-', req.user_agent or '-',
         trans_time,
         additional_info)
     if req.method.upper() == 'REPLICATE':
         self.logger.debug(log_message)
     else:
         self.logger.info(log_message)
     return res(env, start_response)
开发者ID:BillTheBest,项目名称:swift,代码行数:35,代码来源:server.py


示例9: __call__

 def __call__(self, env, start_response):
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get('x-trans-id', None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body='Invalid UTF8')
     else:
         try:
             # disallow methods which have not been marked 'public'
             try:
                 method = getattr(self, req.method)
                 getattr(method, 'publicly_accessible')
             except AttributeError:
                 res = HTTPMethodNotAllowed()
             else:
                 res = method(req)
         except (Exception, Timeout):
             self.logger.exception(_('ERROR __call__ error with %(method)s'
                 ' %(path)s '), {'method': req.method, 'path': req.path})
             res = HTTPInternalServerError(body=traceback.format_exc())
     trans_time = '%.4f' % (time.time() - start_time)
     log_message = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %s' % (
         req.remote_addr,
         time.strftime('%d/%b/%Y:%H:%M:%S +0000',
                       time.gmtime()),
         req.method, req.path,
         res.status.split()[0], res.content_length or '-',
         req.headers.get('x-trans-id', '-'),
         req.referer or '-', req.user_agent or '-',
         trans_time)
     if req.method.upper() == 'REPLICATE':
         self.logger.debug(log_message)
     else:
         self.logger.info(log_message)
     return res(env, start_response)
开发者ID:HodongHwang,项目名称:swift,代码行数:35,代码来源:server.py


示例10: __call__

    def __call__(self, env, start_response):

        req = Request(env)

        if 'd' != req.headers.get('X-Ftype'):
            return self.app(env,start_response)

        self.logger.txn_id = req.headers.get('x-trans-id', None)
        
        if not check_utf8(req.path_info):
            res = jresponse('-1', 'invalid UTF8', req,412)
            
        else:
            try:
                # disallow methods which have not been marked 'public'
                try:
                    method = getattr(self, req.method)
                    getattr(method, 'publicly_accessible')
                except AttributeError:
                    res = jresponse('-1', 'method not allowed', req,405)
                else:
                    res = method(req)

            except (Exception, Timeout):
                self.logger.exception(_('ERROR __call__ error with %(method)s'
                    ' %(path)s '), {'method': req.method, 'path': req.path})
                res = jresponse('-1', 'internal server error', req,500)
                
        return res(env, start_response)
开发者ID:sun3shines,项目名称:swift-1.7.4,代码行数:29,代码来源:server.py


示例11: __call__

 def __call__(self, env, start_response):
     
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get('x-trans-id', None)
     if not check_utf8(req.path_info):
         res = jresponse('-1','Invalid UTF8',req,412)
     else:
         try:
             # disallow methods which have not been marked 'public'
             try:
                 method = getattr(self, req.method)
                 getattr(method, 'publicly_accessible')
             except AttributeError:
                 res = jresponse('-1', 'method not allowed', req,405) 
             else:
                 res = method(req)
                 # if req.method == 'PUT':
                 #    print 'path:   '+req.path +  '      status:  '+str(res.status_int) + '  msg: '+res.body
         except (Exception, Timeout):
             self.logger.exception(_('ERROR __call__ error with %(method)s'
                 ' %(path)s '), {'method': req.method, 'path': req.path})
             res = jresponse('-1', 'InternalServerError', req,500)
     
     return res(env, start_response)
开发者ID:sun7shines,项目名称:Cloudfs,代码行数:25,代码来源:server.py


示例12: get_segments_to_delete_iter

    def get_segments_to_delete_iter(self, req):
        """
        A generator function to be used to delete all the segments and
        sub-segments referenced in a manifest.

        :params req: a swob.Request with an SLO manifest in path
        :raises HTTPPreconditionFailed: on invalid UTF8 in request path
        :raises HTTPBadRequest: on too many buffered sub segments and
                                on invalid SLO manifest path
        """
        if not check_utf8(req.path_info):
            raise HTTPPreconditionFailed(request=req, body="Invalid UTF8 or contains NULL")
        vrs, account, container, obj = req.split_path(4, 4, True)

        segments = [{"sub_slo": True, "name": ("/%s/%s" % (container, obj)).decode("utf-8")}]
        while segments:
            if len(segments) > MAX_BUFFERED_SLO_SEGMENTS:
                raise HTTPBadRequest("Too many buffered slo segments to delete.")
            seg_data = segments.pop(0)
            if seg_data.get("sub_slo"):
                try:
                    segments.extend(self.get_slo_segments(seg_data["name"], req))
                except HTTPException as err:
                    # allow bulk delete response to report errors
                    seg_data["error"] = {"code": err.status_int, "message": err.body}

                # add manifest back to be deleted after segments
                seg_data["sub_slo"] = False
                segments.append(seg_data)
            else:
                seg_data["name"] = seg_data["name"].encode("utf-8")
                yield seg_data
开发者ID:pchng,项目名称:swift,代码行数:32,代码来源:slo.py


示例13: __call__

 def __call__(self, env, start_response):
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get('x-trans-id', None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body='Invalid UTF8 or contains NULL')
     else:
         try:
             # disallow methods which are not publicly accessible
             if req.method not in self.allowed_methods:
                 res = HTTPMethodNotAllowed()
             else:
                 res = getattr(self, req.method)(req)
         except HTTPException as error_response:
             res = error_response
         except (Exception, Timeout):
             self.logger.exception(_('ERROR __call__ error with %(method)s'
                                     ' %(path)s '),
                                   {'method': req.method, 'path': req.path})
             res = HTTPInternalServerError(body=traceback.format_exc())
     if self.log_requests:
         trans_time = time.time() - start_time
         additional_info = ''
         if res.headers.get('x-container-timestamp') is not None:
             additional_info += 'x-container-timestamp: %s' % \
                 res.headers['x-container-timestamp']
         log_msg = get_log_line(req, res, trans_time, additional_info,
                                self.log_format, self.anonymization_method,
                                self.anonymization_salt)
         if req.method.upper() == 'REPLICATE':
             self.logger.debug(log_msg)
         else:
             self.logger.info(log_msg)
     return res(env, start_response)
开发者ID:openstack,项目名称:swift,代码行数:34,代码来源:server.py


示例14: __call__

 def __call__(self, env, start_response):
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get("x-trans-id", None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body="Invalid UTF8")
     else:
         try:
             if hasattr(self, req.method):
                 res = getattr(self, req.method)(req)
             else:
                 res = HTTPMethodNotAllowed()
         except (Exception, Timeout):
             self.logger.exception(
                 _("ERROR __call__ error with %(method)s" " %(path)s "), {"method": req.method, "path": req.path}
             )
             res = HTTPInternalServerError(body=traceback.format_exc())
     trans_time = "%.4f" % (time.time() - start_time)
     log_message = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %s' % (
         req.remote_addr,
         time.strftime("%d/%b/%Y:%H:%M:%S +0000", time.gmtime()),
         req.method,
         req.path,
         res.status.split()[0],
         res.content_length or "-",
         req.headers.get("x-trans-id", "-"),
         req.referer or "-",
         req.user_agent or "-",
         trans_time,
     )
     if req.method.upper() == "REPLICATE":
         self.logger.debug(log_message)
     else:
         self.logger.info(log_message)
     return res(env, start_response)
开发者ID:nicoleLiu,项目名称:swift,代码行数:35,代码来源:server.py


示例15: handle_extract

    def handle_extract(self, req, compress_type):
        """
        :params req: a swob Request
        :params compress_type: specifying the compression type of the tar.
                               Accepts '', 'gz, or 'bz2'
        :raises HTTPException: on unhandled errors
        :returns: a swob response to request
        """
        success_count = 0
        failed_files = []
        existing_containers = set()
        out_content_type = req.accept.best_match(ACCEPTABLE_FORMATS)
        if not out_content_type:
            return HTTPNotAcceptable(request=req)
        if req.content_length is None and req.headers.get("transfer-encoding", "").lower() != "chunked":
            return HTTPBadRequest("Invalid request: no content sent.")
        try:
            vrs, account, extract_base = req.split_path(2, 3, True)
        except ValueError:
            return HTTPNotFound(request=req)
        extract_base = extract_base or ""
        extract_base = extract_base.rstrip("/")
        try:
            tar = tarfile.open(mode="r|" + compress_type, fileobj=req.body_file)
            while True:
                tar_info = tar.next()
                if tar_info is None or len(failed_files) >= self.max_failed_extractions:
                    break
                if tar_info.isfile():
                    obj_path = tar_info.name
                    if obj_path.startswith("./"):
                        obj_path = obj_path[2:]
                    obj_path = obj_path.lstrip("/")
                    if extract_base:
                        obj_path = extract_base + "/" + obj_path
                    if "/" not in obj_path:
                        continue  # ignore base level file

                    destination = "/".join(["", vrs, account, obj_path])
                    container = obj_path.split("/", 1)[0]
                    if not check_utf8(destination):
                        failed_files.append([quote(destination[:MAX_PATH_LENGTH]), HTTPPreconditionFailed().status])
                        continue
                    if tar_info.size > MAX_FILE_SIZE:
                        failed_files.append([quote(destination[:MAX_PATH_LENGTH]), HTTPRequestEntityTooLarge().status])
                        continue
                    if container not in existing_containers:
                        try:
                            self.create_container(req, "/".join(["", vrs, account, container]))
                            existing_containers.add(container)
                        except CreateContainerError, err:
                            if err.status_int == HTTP_UNAUTHORIZED:
                                return HTTPUnauthorized(request=req)
                            failed_files.append([quote(destination[:MAX_PATH_LENGTH]), err.status])
                            continue
                        except ValueError:
                            failed_files.append([quote(destination[:MAX_PATH_LENGTH]), HTTP_BAD_REQUEST])
                            continue
                        if len(existing_containers) > self.max_containers:
                            return HTTPBadRequest("More than %d base level containers in tar." % self.max_containers)
开发者ID:ChristopherMacGown,项目名称:swift,代码行数:60,代码来源:bulk.py


示例16: test_check_utf8_lone_surrogates

    def test_check_utf8_lone_surrogates(self):
        self.assertFalse(constraints.check_utf8(b'\xed\xa0\xbc'))
        self.assertFalse(constraints.check_utf8(u'\ud83c'))
        self.assertFalse(constraints.check_utf8(b'\xed\xb9\x88'))
        self.assertFalse(constraints.check_utf8(u'\ude48'))

        self.assertFalse(constraints.check_utf8(u'\ud800'))
        self.assertFalse(constraints.check_utf8(u'\udc00'))
        self.assertFalse(constraints.check_utf8(u'\udcff'))
        self.assertFalse(constraints.check_utf8(u'\udfff'))
开发者ID:jgmerritt,项目名称:swift,代码行数:10,代码来源:test_constraints.py


示例17: handle_delete

    def handle_delete(self, req):
        """
        :params req: a swob Request
        :raises HTTPException: on unhandled errors
        :returns: a swob Response
        """
        try:
            vrs, account, _junk = req.split_path(2, 3, True)
        except ValueError:
            return HTTPNotFound(request=req)

        incoming_format = req.headers.get("Content-Type")
        if incoming_format and not incoming_format.startswith("text/plain"):
            # For now only accept newline separated object names
            return HTTPNotAcceptable(request=req)
        out_content_type = req.accept.best_match(ACCEPTABLE_FORMATS)
        if not out_content_type:
            return HTTPNotAcceptable(request=req)

        objs_to_delete = self.get_objs_to_delete(req)
        failed_files = []
        success_count = not_found_count = 0
        failed_file_response_type = HTTPBadRequest
        for obj_to_delete in objs_to_delete:
            obj_to_delete = obj_to_delete.strip().lstrip("/")
            if not obj_to_delete:
                continue
            obj_to_delete = unquote(obj_to_delete)
            delete_path = "/".join(["", vrs, account, obj_to_delete])
            if not check_utf8(delete_path):
                failed_files.append([quote(delete_path), HTTPPreconditionFailed().status])
                continue
            new_env = req.environ.copy()
            new_env["PATH_INFO"] = delete_path
            del (new_env["wsgi.input"])
            new_env["CONTENT_LENGTH"] = 0
            new_env["HTTP_USER_AGENT"] = "%s BulkDelete" % req.environ.get("HTTP_USER_AGENT")
            delete_obj_req = Request.blank(delete_path, new_env)
            resp = delete_obj_req.get_response(self.app)
            if resp.status_int // 100 == 2:
                success_count += 1
            elif resp.status_int == HTTP_NOT_FOUND:
                not_found_count += 1
            elif resp.status_int == HTTP_UNAUTHORIZED:
                return HTTPUnauthorized(request=req)
            else:
                if resp.status_int // 100 == 5:
                    failed_file_response_type = HTTPBadGateway
                failed_files.append([quote(delete_path), resp.status])

        resp_body = self.get_response_body(
            out_content_type, {"Number Deleted": success_count, "Number Not Found": not_found_count}, failed_files
        )
        if (success_count or not_found_count) and not failed_files:
            return HTTPOk(resp_body, content_type=out_content_type)
        if failed_files:
            return failed_file_response_type(resp_body, content_type=out_content_type)
        return HTTPBadRequest("Invalid bulk delete.")
开发者ID:ChristopherMacGown,项目名称:swift,代码行数:58,代码来源:bulk.py


示例18: __call__

    def __call__(self, env, start_response):
        """WSGI Application entry point for the Swift Object Server."""
        start_time = time.time()
        req = Request(env)
        self.logger.txn_id = req.headers.get("x-trans-id", None)

        if not check_utf8(req.path_info):
            res = HTTPPreconditionFailed(body="Invalid UTF8 or contains NULL")
        else:
            try:
                # disallow methods which have not been marked 'public'
                try:
                    method = getattr(self, req.method)
                    getattr(method, "publicly_accessible")
                    replication_method = getattr(method, "replication", False)
                    if self.replication_server is not None and self.replication_server != replication_method:
                        raise AttributeError("Not allowed method.")
                except AttributeError:
                    res = HTTPMethodNotAllowed()
                else:
                    res = method(req)
            except DiskFileCollision:
                res = HTTPForbidden(request=req)
            except HTTPException as error_response:
                res = error_response
            except (Exception, Timeout):
                self.logger.exception(
                    _("ERROR __call__ error with %(method)s" " %(path)s "), {"method": req.method, "path": req.path}
                )
                res = HTTPInternalServerError(body=traceback.format_exc())
        trans_time = time.time() - start_time
        if self.log_requests:
            log_line = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %.4f' % (
                req.remote_addr,
                time.strftime("%d/%b/%Y:%H:%M:%S +0000", time.gmtime()),
                req.method,
                req.path,
                res.status.split()[0],
                res.content_length or "-",
                req.referer or "-",
                req.headers.get("x-trans-id", "-"),
                req.user_agent or "-",
                trans_time,
            )
            if req.method in ("REPLICATE", "REPLICATION") or "X-Backend-Replication" in req.headers:
                self.logger.debug(log_line)
            else:
                self.logger.info(log_line)
        if req.method in ("PUT", "DELETE"):
            slow = self.slow - trans_time
            if slow > 0:
                sleep(slow)
        return res(env, start_response)
开发者ID:vbaret,项目名称:swift,代码行数:53,代码来源:server.py


示例19: test_check_utf8_non_canonical

 def test_check_utf8_non_canonical(self):
     self.assertFalse(constraints.check_utf8(b'\xed\xa0\xbc\xed\xbc\xb8'))
     self.assertTrue(constraints.check_utf8(u'\U0001f338'))
     self.assertTrue(constraints.check_utf8(b'\xf0\x9f\x8c\xb8'))
     self.assertTrue(constraints.check_utf8(u'\U0001f338'.encode('utf8')))
     self.assertFalse(constraints.check_utf8(b'\xed\xa0\xbd\xed\xb9\x88'))
     self.assertTrue(constraints.check_utf8(u'\U0001f648'))
开发者ID:jgmerritt,项目名称:swift,代码行数:7,代码来源:test_constraints.py


示例20: split_path

def split_path(path, minsegs=1, maxsegs=None, rest_with_last=False):
    """
    This is a copy/paste of swift.common.utils.split_path.  I will
    probably be adding the unquote into swift's version soon and this
    will prevent dependencies on that.
    Validate and split the given HTTP request path.

    **Examples**::

        ['a'] = split_path('/a')
        ['a', None] = split_path('/a', 1, 2)
        ['a', 'c'] = split_path('/a/c', 1, 2)
        ['a', 'c', 'o/r'] = split_path('/a/c/o/r', 1, 3, True)

    :param path: HTTP Request path to be split
    :param minsegs: Minimum number of segments to be extracted
    :param maxsegs: Maximum number of segments to be extracted
    :param rest_with_last: If True, trailing data will be returned as part
                           of last segment.  If False, and there is
                           trailing data, raises ValueError.
    :returns: list of segments with a length of maxsegs (non-existant
              segments will return as None)
    :raises: ValueError if given an invalid path
    :raises: InvalidUtf8 if path contains invalid UTF-8
    """
    path = unquote(path)
    if not check_utf8(path):
        raise InvalidUtf8('Invalid UTF8')
    if not maxsegs:
        maxsegs = minsegs
    if minsegs > maxsegs:
        raise ValueError('minsegs > maxsegs: %d > %d' % (minsegs, maxsegs))
    if rest_with_last:
        segs = path.split('/', maxsegs)
        minsegs += 1
        maxsegs += 1
        count = len(segs)
        if segs[0] or count < minsegs or count > maxsegs or \
                '' in segs[1:minsegs]:
            raise ValueError('Invalid path: %s' % quote(path))
    else:
        minsegs += 1
        maxsegs += 1
        segs = path.split('/', maxsegs)
        count = len(segs)
        if segs[0] or count < minsegs or count > maxsegs + 1 or \
                '' in segs[1:minsegs] or (count == maxsegs + 1 and
                segs[maxsegs]):
            raise ValueError('Invalid path: %s' % quote(path))
    segs = segs[1:maxsegs]
    segs.extend([None] * (maxsegs - 1 - len(segs)))
    return segs
开发者ID:pandemicsyn,项目名称:sos,代码行数:52,代码来源:origin.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python constraints.reload_constraints函数代码示例发布时间:2022-05-27
下一篇:
Python constraints.check_object_creation函数代码示例发布时间: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