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

Python six.text_type函数代码示例

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

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



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

示例1: fetch_git_sha

def fetch_git_sha(path, head=None):
    """
    >>> fetch_git_sha(os.path.dirname(__file__))
    """
    if not head:
        head_path = os.path.join(path, '.git', 'HEAD')
        if not os.path.exists(head_path):
            raise InvalidGitRepository('Cannot identify HEAD for git repository at %s' % (path,))

        with open(head_path, 'r') as fp:
            head = six.text_type(fp.read()).strip()

        if head.startswith('ref: '):
            revision_file = os.path.join(
                path, '.git', *head.rsplit(' ', 1)[-1].split('/')
            )
        else:
            revision_file = os.path.join(path, '.git', head)
    else:
        revision_file = os.path.join(path, '.git', 'refs', 'heads', head)

    if not os.path.exists(revision_file):
        if not os.path.exists(os.path.join(path, '.git')):
            raise InvalidGitRepository('%s does not seem to be the root of a git repository' % (path,))
        raise InvalidGitRepository('Unable to find ref to head "%s" in repository' % (head,))

    fh = open(revision_file, 'r')
    try:
        return six.text_type(fh.read()).strip()
    finally:
        fh.close()
开发者ID:noirbizarre,项目名称:raven-python,代码行数:31,代码来源:versioning.py


示例2: transform

    def transform(self, value, **kwargs):
        """
        Primary function which handles recursively transforming
        values via their serializers
        """
        if value is None:
            return None

        objid = id(value)
        if objid in self.context:
            return '<...>'
        self.context.add(objid)

        try:
            for serializer in self.serializers:
                if serializer.can(value):
                    try:
                        return serializer.serialize(value, **kwargs)
                    except Exception as e:
                        logger.exception(e)
                        return six.text_type(type(value))

            # if all else fails, lets use the repr of the object
            try:
                return repr(value)
            except Exception as e:
                logger.exception(e)
                # It's common case that a model's __unicode__ definition may try to query the database
                # which if it was not cleaned up correctly, would hit a transaction aborted exception
                return six.text_type(type(value))
        finally:
            self.context.remove(objid)
开发者ID:Aaron1011,项目名称:domorereps-android,代码行数:32,代码来源:manager.py


示例3: test_dict_keys_utf8_as_unicode

    def test_dict_keys_utf8_as_unicode(self):
        x = {
            six.text_type('\u05e8\u05d5\u05e0\u05d9\u05ea \u05de\u05d2\u05df'): 'bar'
        }

        result = transform(x)
        assert type(result) is dict
        keys = list(result.keys())
        assert len(keys) == 1
        assert keys[0] == six.text_type("u'\u05e8\u05d5\u05e0\u05d9\u05ea \u05de\u05d2\u05df'")
开发者ID:binarydud,项目名称:raven-python,代码行数:10,代码来源:tests.py


示例4: test_import_string

def test_import_string():
    new_raven = import_string('raven')
    assert new_raven is raven

    # this will test unicode on python2
    new_raven = import_string(six.text_type('raven'))
    assert new_raven is raven

    new_client = import_string('raven.Client')
    assert new_client is raven.Client

    # this will test unicode on python2
    new_client = import_string(six.text_type('raven.Client'))
    assert new_client is raven.Client
开发者ID:CGenie,项目名称:raven-python,代码行数:14,代码来源:test_imports.py


示例5: recurse

 def recurse(self, value, max_depth=6, _depth=0, **kwargs):
     """
     Given ``value``, recurse (using the parent serializer) to handle
     coercing of newly defined values.
     """
     _depth += 1
     if _depth >= max_depth:
         try:
             value = six.text_type(repr(value))
         except Exception as e:
             import traceback
             traceback.print_exc()
             self.manager.logger.exception(e)
             return six.text_type(type(value))
     return self.manager.transform(value, max_depth=max_depth, _depth=_depth, **kwargs)
开发者ID:Danik1601,项目名称:Plex-Trakt-Scrobbler,代码行数:15,代码来源:base.py


示例6: serialize

 def serialize(self, value, **kwargs):
     # try to return a reasonable string that can be decoded
     # correctly by the server so it doesn't show up as \uXXX for each
     # unicode character
     # e.g. we want the output to be like: "u'רונית מגן'"
     string_max_length = kwargs.get('string_max_length', None)
     return repr(six.text_type('%s')) % (value[:string_max_length],)
开发者ID:jmagnusson,项目名称:raven-python,代码行数:7,代码来源:base.py


示例7: __init__

    def __init__(self, dsn=None, raise_send_errors=False, transport=None,
                 install_sys_hook=True, **options):
        global Raven

        o = options

        self.configure_logging()

        self.raise_send_errors = raise_send_errors

        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger(
            '%s.%s' % (cls.__module__, cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')
        self.uncaught_logger = logging.getLogger('sentry.errors.uncaught')

        self._transport_cache = {}
        self.set_dsn(dsn, transport)

        self.include_paths = set(o.get('include_paths') or [])
        self.exclude_paths = set(o.get('exclude_paths') or [])
        self.name = six.text_type(o.get('name') or o.get('machine') or defaults.NAME)
        self.auto_log_stacks = bool(
            o.get('auto_log_stacks') or defaults.AUTO_LOG_STACKS)
        self.capture_locals = bool(
            o.get('capture_locals', defaults.CAPTURE_LOCALS))
        self.string_max_length = int(
            o.get('string_max_length') or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(
            o.get('list_max_length') or defaults.MAX_LENGTH_LIST)
        self.site = o.get('site')
        self.include_versions = o.get('include_versions', True)
        self.processors = o.get('processors')
        if self.processors is None:
            self.processors = defaults.PROCESSORS

        context = o.get('context')
        if context is None:
            context = {'sys.argv': sys.argv[:]}
        self.extra = context
        self.tags = o.get('tags') or {}
        self.environment = o.get('environment') or None
        self.release = o.get('release') or os.environ.get('HEROKU_SLUG_COMMIT')

        self.module_cache = ModuleProxyCache()

        if not self.is_enabled():
            self.logger.info(
                'Raven is not configured (logging is disabled). Please see the'
                ' documentation for more information.')

        if Raven is None:
            Raven = self

        self._context = Context()

        if install_sys_hook:
            self.install_sys_hook()
开发者ID:simudream,项目名称:raven-python,代码行数:60,代码来源:base.py


示例8: serialize

 def serialize(self, value, **kwargs):
     # EPIC HACK
     # handles lazy model instances (which are proxy values that dont easily give you the actual function)
     pre = value.__class__.__name__[1:]
     if hasattr(value, '%s__func' % pre):
         value = getattr(value, '%s__func' % pre)(*getattr(value, '%s__args' % pre), **getattr(value, '%s__kw' % pre))
     else:
         return self.recurse(six.text_type(value))
     return self.recurse(value, **kwargs)
开发者ID:1Anastaska,项目名称:raven-python,代码行数:9,代码来源:serializers.py


示例9: force_text

def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_text, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    # Handle the common case first, saves 30-40% when s is an instance of
    # six.text_type. This function gets called often in that setting.
    if isinstance(s, six.text_type):
        return s
    if strings_only and is_protected_type(s):
        return s
    try:
        if not isinstance(s, six.string_types):
            if hasattr(s, '__unicode__'):
                s = s.__unicode__()
            else:
                if six.PY3:
                    if isinstance(s, bytes):
                        s = six.text_type(s, encoding, errors)
                    else:
                        s = six.text_type(s)
                else:
                    s = six.text_type(bytes(s), encoding, errors)
        else:
            # Note: We use .decode() here, instead of six.text_type(s, encoding,
            # errors), so that if s is a SafeBytes, it ends up being a
            # SafeText at the end.
            s = s.decode(encoding, errors)
    except UnicodeDecodeError as e:
        if not isinstance(s, Exception):
            raise UnicodeDecodeError(s, *e.args)
        else:
            # If we get to here, the caller has passed in an Exception
            # subclass populated with non-ASCII bytestring data without a
            # working unicode method. Try to handle this without raising a
            # further exception by individually forcing the exception args
            # to unicode.
            s = ' '.join([force_text(arg, encoding, strings_only,
                    errors) for arg in s])
    return s
开发者ID:Aaron1011,项目名称:domorereps-android,代码行数:42,代码来源:encoding.py


示例10: to_unicode

def to_unicode(value):
    try:
        value = six.text_type(force_text(value))
    except (UnicodeEncodeError, UnicodeDecodeError):
        value = '(Error decoding value)'
    except Exception:  # in some cases we get a different exception
        try:
            value = six.binary_type(repr(type(value)))
        except Exception:
            value = '(Error decoding value)'
    return value
开发者ID:Aaron1011,项目名称:domorereps-android,代码行数:11,代码来源:encoding.py


示例11: test_dict_keys_utf8_as_unicode

    def test_dict_keys_utf8_as_unicode(self):
        x = {six.text_type("\u05e8\u05d5\u05e0\u05d9\u05ea \u05de\u05d2\u05df"): "bar"}

        result = transform(x)
        assert type(result) is dict
        keys = list(result.keys())
        assert len(keys) == 1
        if six.PY3:
            expected = "'\u05e8\u05d5\u05e0\u05d9\u05ea \u05de\u05d2\u05df'"
        else:
            expected = "u'\u05e8\u05d5\u05e0\u05d9\u05ea \u05de\u05d2\u05df'"
        assert keys[0] == expected
开发者ID:flupke,项目名称:raven,代码行数:12,代码来源:tests.py


示例12: sanitize

    def sanitize(self, key, value):
        if value is None:
            return

        if isinstance(value, six.string_types) and self.VALUES_RE.match(value):
            return self.MASK

        if not key:  # key can be a NoneType
            return value

        key = six.text_type(key).lower()
        for field in self.FIELDS:
            if field in key:
                # store mask as a fixed length for security
                return self.MASK
        return value
开发者ID:CGenie,项目名称:raven-python,代码行数:16,代码来源:processors.py


示例13: gethostname

def gethostname():
    if not hasattr(socket, 'gethostname'):
        return None

    hostname = socket.gethostname()

    if isinstance(hostname, six.text_type):
        return hostname

    try:
        return six.text_type(hostname)
    except UnicodeError:
        pass

    try:
        return hostname.decode('unicode-escape')
    except UnicodeError:
        pass

    return None
开发者ID:Danik1601,项目名称:Plex-Trakt-Scrobbler,代码行数:20,代码来源:__init__.py


示例14: test_real_gettext_lazy

 def test_real_gettext_lazy(self):
     d = {six.text_type("lazy_translation"): gettext_lazy(six.text_type("testing"))}
     key = "'lazy_translation'" if six.PY3 else "u'lazy_translation'"
     value = "'testing'" if six.PY3 else "u'testing'"
     assert transform(d) == {key: value}
开发者ID:recht,项目名称:raven-python,代码行数:5,代码来源:tests.py


示例15: __init__

    def __init__(self, dsn=None, raise_send_errors=False, **options):
        global Raven

        o = options

        self.configure_logging()

        self.raise_send_errors = raise_send_errors

        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger("%s.%s" % (cls.__module__, cls.__name__))
        self.error_logger = logging.getLogger("sentry.errors")

        if dsn is None and os.environ.get("SENTRY_DSN"):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.debug(msg)
            dsn = os.environ["SENTRY_DSN"]

        if dsn:
            # TODO: should we validate other options weren't sent?
            urlparts = urlparse(dsn)
            self.logger.debug(
                "Configuring Raven for host: %s://%s:%s" % (urlparts.scheme, urlparts.netloc, urlparts.path)
            )
            dsn_config = raven.load(dsn, transport_registry=self._registry)
            servers = dsn_config["SENTRY_SERVERS"]
            project = dsn_config["SENTRY_PROJECT"]
            public_key = dsn_config["SENTRY_PUBLIC_KEY"]
            secret_key = dsn_config["SENTRY_SECRET_KEY"]
            transport_options = dsn_config.get("SENTRY_TRANSPORT_OPTIONS", {})
        else:
            if o.get("servers"):
                warnings.warn("Manually configured connections are deprecated. Switch to a DSN.", DeprecationWarning)
            servers = o.get("servers")
            project = o.get("project")
            public_key = o.get("public_key")
            secret_key = o.get("secret_key")
            transport_options = {}

        self.servers = servers
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT
        self.transport_options = transport_options

        self.include_paths = set(o.get("include_paths") or [])
        self.exclude_paths = set(o.get("exclude_paths") or [])
        self.name = six.text_type(o.get("name") or defaults.NAME)
        self.auto_log_stacks = bool(o.get("auto_log_stacks") or defaults.AUTO_LOG_STACKS)
        self.capture_locals = bool(o.get("capture_locals", defaults.CAPTURE_LOCALS))
        self.string_max_length = int(o.get("string_max_length") or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(o.get("list_max_length") or defaults.MAX_LENGTH_LIST)
        self.site = o.get("site", defaults.SITE)
        self.include_versions = o.get("include_versions", True)
        self.processors = o.get("processors")
        if self.processors is None:
            self.processors = defaults.PROCESSORS

        context = o.get("context")
        if context is None:
            context = {"sys.argv": sys.argv[:]}
        self.extra = context
        self.tags = o.get("tags") or {}

        self.module_cache = ModuleProxyCache()

        # servers may be set to a NoneType (for Django)
        if not self.is_enabled():
            self.logger.info(
                "Raven is not configured (logging is disabled). Please see the" " documentation for more information."
            )

        if Raven is None:
            Raven = self

        self._context = Context()
开发者ID:htomika,项目名称:gaeFeedFind,代码行数:78,代码来源:base.py


示例16: test_correct_unicode

    def test_correct_unicode(self):
        # 'רונית מגן'
        x = six.text_type('\u05e8\u05d5\u05e0\u05d9\u05ea \u05de\u05d2\u05df')

        result = transform(x)
        assert result == six.text_type("u'\u05e8\u05d5\u05e0\u05d9\u05ea \u05de\u05d2\u05df'")
开发者ID:binarydud,项目名称:raven-python,代码行数:6,代码来源:tests.py


示例17: _emit

    def _emit(self, record, **kwargs):
        data = {}

        extra = getattr(record, 'data', None)
        if not isinstance(extra, dict):
            if extra:
                extra = {'data': extra}
            else:
                extra = {}

        for k, v in six.iteritems(vars(record)):
            if k in RESERVED:
                continue
            if k.startswith('_'):
                continue
            if '.' not in k and k not in ('culprit', 'server_name', 'fingerprint'):
                extra[k] = v
            else:
                data[k] = v

        stack = getattr(record, 'stack', None)
        if stack is True:
            stack = iter_stack_frames()

        if stack:
            stack = self._get_targetted_stack(stack, record)

        date = datetime.datetime.utcfromtimestamp(record.created)
        event_type = 'raven.events.Message'
        handler_kwargs = {
            'params': record.args,
        }
        try:
            handler_kwargs['message'] = six.text_type(record.msg)
        except UnicodeDecodeError:
            # Handle binary strings where it should be unicode...
            handler_kwargs['message'] = repr(record.msg)[1:-1]

        try:
            handler_kwargs['formatted'] = six.text_type(record.message)
        except UnicodeDecodeError:
            # Handle binary strings where it should be unicode...
            handler_kwargs['formatted'] = repr(record.message)[1:-1]

        # If there's no exception being processed, exc_info may be a 3-tuple of None
        # http://docs.python.org/library/sys.html#sys.exc_info
        if record.exc_info and all(record.exc_info):
            # capture the standard message first so that we ensure
            # the event is recorded as an exception, in addition to having our
            # message interface attached
            handler = self.client.get_handler(event_type)
            data.update(handler.capture(**handler_kwargs))

            event_type = 'raven.events.Exception'
            handler_kwargs = {'exc_info': record.exc_info}

        # HACK: discover a culprit when we normally couldn't
        elif not (data.get('stacktrace') or data.get('culprit')) and (record.name or record.funcName):
            culprit = label_from_frame({'module': record.name, 'function': record.funcName})
            if culprit:
                data['culprit'] = culprit

        data['level'] = record.levelno
        data['logger'] = record.name

        if hasattr(record, 'tags'):
            kwargs['tags'] = record.tags
        elif self.tags:
            kwargs['tags'] = self.tags

        kwargs.update(handler_kwargs)

        return self.client.capture(
            event_type, stack=stack, data=data,
            extra=extra, date=date, **kwargs)
开发者ID:simudream,项目名称:raven-python,代码行数:75,代码来源:logging.py


示例18: __unicode__

 def __unicode__(self):
     return six.text_type(self.base_url)
开发者ID:hannosch,项目名称:raven-python,代码行数:2,代码来源:remote.py


示例19: decode_str

 def decode_str(line):
     if isinstance(line, six.text_type):
         return line
     else:
         return six.text_type(line, encoding, 'replace')
开发者ID:binarydud,项目名称:raven-python,代码行数:5,代码来源:stacks.py


示例20: __unicode__

 def __unicode__(self):
     return six.text_type("%s: %s" % (self.message, self.code))
开发者ID:CGenie,项目名称:raven-python,代码行数:2,代码来源:exceptions.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python stacks.get_culprit函数代码示例发布时间:2022-05-26
下一篇:
Python six.iteritems函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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