本文整理匯總了Python中six.text_type方法的典型用法代碼示例。如果您正苦於以下問題:Python six.text_type方法的具體用法?Python six.text_type怎麽用?Python six.text_type使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類six
的用法示例。
在下文中一共展示了six.text_type方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_prep_value
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def get_prep_value(self, value):
if value is self.Empty or value is None:
return '' # CharFields should use '' as their empty value, rather than None
if isinstance(value, six.string_types):
value = self.KEY_CLASS.from_string(value)
assert isinstance(value, self.KEY_CLASS), "%s is not an instance of %s" % (value, self.KEY_CLASS)
serialized_key = six.text_type(_strip_value(value))
if serialized_key.endswith('\n'):
# An opaque key object serialized to a string with a trailing newline.
# Log the value - but do not modify it.
log.warning(u'{}:{}:{}:get_prep_value: Invalid key: {}.'.format(
self.model._meta.db_table, # pylint: disable=protected-access
self.name,
self.KEY_CLASS.__name__,
repr(serialized_key)
))
return serialized_key
示例2: test_translate_message_with_param_from_unicoded_obj
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def test_translate_message_with_param_from_unicoded_obj(self,
mock_translation):
message_with_params = 'A message: %s'
es_translation = 'A message in Spanish: %s'
param = 'A Message param'
translations = {message_with_params: es_translation}
translator = fakes.FakeTranslations.translator({'es': translations})
mock_translation.side_effect = translator
msg = _message.Message(message_with_params)
msg = msg % param
default_translation = message_with_params % param
expected_translation = es_translation % param
obj = utils.SomeObject(msg)
unicoded_obj = six.text_type(obj)
self.assertEqual(expected_translation, unicoded_obj.translation('es'))
self.assertEqual(default_translation, unicoded_obj.translation('XX'))
示例3: property_value_to_bytes
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def property_value_to_bytes(value):
"""
Return a byte string, which represents the given ``value`` in a way
suitable as raw value of an udev property.
If ``value`` is a boolean object, it is converted to ``'1'`` or ``'0'``,
depending on whether ``value`` is ``True`` or ``False``. If ``value`` is a
byte string already, it is returned unchanged. Anything else is simply
converted to a unicode string, and then passed to
:func:`ensure_byte_string`.
"""
# udev represents boolean values as 1 or 0, therefore an explicit
# conversion to int is required for boolean values
if isinstance(value, bool):
value = int(value)
if isinstance(value, bytes):
return value
else:
return ensure_byte_string(six.text_type(value))
示例4: _escape_token
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def _escape_token(token, alphabet):
"""Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
token: A unicode string to be escaped.
alphabet: A set of all characters in the vocabulary's alphabet.
Returns:
escaped_token: An escaped unicode string.
Raises:
ValueError: If the provided token is not unicode.
"""
if not isinstance(token, six.text_type):
raise ValueError("Expected string type for token, got %s" % type(token))
token = token.replace(u"\\", u"\\\\").replace(u"_", u"\\u")
ret = [c if c in alphabet and c != u"\n" else r"\%d;" % ord(c) for c in token]
return u"".join(ret) + "_"
示例5: is_payfast_ip_address
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def is_payfast_ip_address(ip_address_str):
"""
Return True if ip_address_str matches one of PayFast's server IP addresses.
Setting: `PAYFAST_IP_ADDRESSES`
:type ip_address_str: str
:rtype: bool
"""
# TODO: Django system check for validity?
payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES',
conf.DEFAULT_PAYFAST_IP_ADDRESSES)
if sys.version_info < (3,):
# Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors.
# (On Python 3, this should generally not happen:
# let unexpected bytes values fail as expected.)
ip_address_str = unicode(ip_address_str) # noqa: F821
payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses] # noqa: F821
return any(ip_address(ip_address_str) in ip_network(payfast_address)
for payfast_address in payfast_ip_addresses)
示例6: _prepare_signable_fields
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def _prepare_signable_fields(
valid_field_order, # type: Sequence[str]
data_fields, # type: Mapping[str, str]
): # type: (...) -> SignableFields
"""
Prepare PayFast submission variables for signing, using the given field order.
:raise ValueError:
If `data_fields` contains any unexpected field names not in `valid_field_order`.
"""
present_fields = (set(data_fields.keys()) if sys.version_info < (3,) else
data_fields.keys())
extra_fields = present_fields - set(valid_field_order)
if extra_fields:
raise ValueError('Data contains unexpected fields: {!r}'.format(extra_fields))
return [
(name, data_fields[name]) for name in valid_field_order
if name in data_fields
]
示例7: __init__
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def __init__(self, *args, **kwargs):
super(ResourceTypeSchemaManager, self).__init__(*args, **kwargs)
type_schemas = tuple([ext.plugin.meta_schema()
for ext in self.extensions])
self._schema = voluptuous.Schema({
"name": six.text_type,
voluptuous.Required("attributes", default={}): {
six.text_type: voluptuous.Any(*tuple(type_schemas))
}
})
type_schemas = tuple([ext.plugin.meta_schema(for_update=True)
for ext in self.extensions])
self._schema_for_update = voluptuous.Schema({
"name": six.text_type,
voluptuous.Required("attributes", default={}): {
six.text_type: voluptuous.Any(*tuple(type_schemas))
}
})
示例8: get_pagination_options
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def get_pagination_options(params, default):
try:
opts = voluptuous.Schema({
voluptuous.Required(
"limit", default=pecan.request.conf.api.max_limit):
voluptuous.All(voluptuous.Coerce(int),
voluptuous.Range(min=1),
voluptuous.Clamp(
min=1, max=pecan.request.conf.api.max_limit)),
"marker": six.text_type,
voluptuous.Required("sort", default=default):
voluptuous.All(
voluptuous.Coerce(arg_to_list),
[six.text_type]),
}, extra=voluptuous.REMOVE_EXTRA)(params)
except voluptuous.Invalid as e:
abort(400, {"cause": "Argument value error",
"reason": str(e)})
opts['sorts'] = opts['sort']
del opts['sort']
return opts
示例9: patch
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def patch(self):
ap = pecan.request.indexer.get_archive_policy(self.archive_policy)
if not ap:
abort(404, six.text_type(
indexer.NoSuchArchivePolicy(self.archive_policy)))
enforce("update archive policy", ap)
body = deserialize_and_validate(voluptuous.Schema({
voluptuous.Required("definition"): ArchivePolicyDefinitionSchema,
}))
# Validate the data
try:
ap_items = [archive_policy.ArchivePolicyItem(**item) for item in
body['definition']]
except ValueError as e:
abort(400, six.text_type(e))
try:
return pecan.request.indexer.update_archive_policy(
self.archive_policy, ap_items)
except indexer.UnsupportedArchivePolicyChange as e:
abort(400, six.text_type(e))
示例10: post
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def post(self):
enforce("create archive policy rule", {})
ArchivePolicyRuleSchema = voluptuous.Schema({
voluptuous.Required("name"): six.text_type,
voluptuous.Required("metric_pattern"): six.text_type,
voluptuous.Required("archive_policy_name"): six.text_type,
})
body = deserialize_and_validate(ArchivePolicyRuleSchema)
enforce("create archive policy rule", body)
try:
ap = pecan.request.indexer.create_archive_policy_rule(
body['name'], body['metric_pattern'],
body['archive_policy_name']
)
except indexer.ArchivePolicyRuleAlreadyExists as e:
abort(409, six.text_type(e))
except indexer.NoSuchArchivePolicy as e:
abort(400, e)
location = "/archive_policy_rule/" + ap.name
set_resp_location_hdr(location)
pecan.response.status = 201
return ap
示例11: _lookup
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def _lookup(self, name, *remainder):
m = pecan.request.indexer.list_metrics(
details=True,
attribute_filter={"and": [
{"=": {"name": name}},
{"=": {"resource_id": self.resource_id}},
]})
if m:
return MetricController(m[0]), remainder
resource = pecan.request.indexer.get_resource(self.resource_type,
self.resource_id)
if resource:
abort(404, six.text_type(indexer.NoSuchMetric(name)))
else:
abort(404, six.text_type(indexer.NoSuchResource(self.resource_id)))
示例12: test_delete_resource_with_metrics
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def test_delete_resource_with_metrics(self):
metric = self.app.post_json(
"/v1/metric",
params={'archive_policy_name': "high"})
metric_id = json.loads(metric.text)['id']
metric_name = six.text_type(uuid.uuid4())
self.attributes['metrics'] = {metric_name: metric_id}
self.app.get("/v1/metric/" + metric_id,
status=200)
self.app.post_json("/v1/resource/" + self.resource_type,
params=self.attributes)
self.app.get("/v1/resource/" + self.resource_type + "/"
+ self.attributes['id'],
status=200)
self.app.delete("/v1/resource/" + self.resource_type + "/"
+ self.attributes['id'],
status=204)
self.app.get("/v1/resource/" + self.resource_type + "/"
+ self.attributes['id'],
status=404)
self.app.get("/v1/metric/" + metric_id,
status=404)
示例13: __mod__
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def __mod__(self, other):
# When we mod a Message we want the actual operation to be performed
# by the base class (i.e. unicode()), the only thing we do here is
# save the original msgid and the parameters in case of a translation
params = self._sanitize_mod_params(other)
unicode_mod = self._safe_translate(six.text_type(self), params)
modded = Message(self.msgid,
msgtext=unicode_mod,
params=params,
domain=self.domain)
return modded
示例14: _copy_param
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def _copy_param(self, param):
try:
return copy.deepcopy(param)
except Exception:
# Fallback to casting to unicode this will handle the
# python code-like objects that can't be deep-copied
return six.text_type(param)
示例15: translate
# 需要導入模塊: import six [as 別名]
# 或者: from six import text_type [as 別名]
def translate(obj, desired_locale=None):
"""Gets the translated unicode representation of the given object.
If the object is not translatable it is returned as-is.
If the desired_locale argument is None the object is translated to
the system locale.
:param obj: the object to translate
:param desired_locale: the locale to translate the message to, if None the
default system locale will be used
:returns: the translated object in unicode, or the original object if
it could not be translated
"""
from oslo_i18n import _message # avoid circular dependency at module level
message = obj
if not isinstance(message, _message.Message):
# If the object to translate is not already translatable,
# let's first get its unicode representation
message = six.text_type(obj)
if isinstance(message, _message.Message):
# Even after unicoding() we still need to check if we are
# running with translatable unicode before translating
return message.translation(desired_locale)
return obj