本文整理汇总了Python中raven.utils.six.text_type函数的典型用法代码示例。如果您正苦于以下问题:Python text_type函数的具体用法?Python text_type怎么用?Python text_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了text_type函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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)
示例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'")
示例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
示例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)
示例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],)
示例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()
示例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)
示例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
示例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
示例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
示例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
示例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
示例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}
示例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()