本文整理汇总了Python中werkzeug._compat.text_type函数的典型用法代码示例。如果您正苦于以下问题:Python text_type函数的具体用法?Python text_type怎么用?Python text_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了text_type函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: escape
def escape(s, quote=None):
"""Replace special characters "&", "<", ">" and (") to HTML-safe sequences.
There is a special handling for `None` which escapes to an empty string.
.. versionchanged:: 0.9
`quote` is now implicitly on.
:param s: the string to escape.
:param quote: ignored.
"""
if s is None:
return ''
elif hasattr(s, '__html__'):
return text_type(s.__html__())
elif not isinstance(s, string_types):
s = text_type(s)
if quote is not None:
from warnings import warn
warn(
"The 'quote' parameter is no longer used as of version 0.9"
" and will be removed in version 1.0.",
DeprecationWarning,
stacklevel=2,
)
s = s.replace('&', '&').replace('<', '<') \
.replace('>', '>').replace('"', """)
return s
示例2: test_exception_repr
def test_exception_repr():
exc = exceptions.NotFound()
assert text_type(exc) == '404: Not Found'
assert repr(exc) == "<NotFound '404: Not Found'>"
exc = exceptions.NotFound('Not There')
assert text_type(exc) == '404: Not Found'
assert repr(exc) == "<NotFound '404: Not Found'>"
示例3: test_exception_repr
def test_exception_repr(self):
exc = exceptions.NotFound()
self.assert_equal(text_type(exc), '404: Not Found')
self.assert_equal(repr(exc), "<NotFound '404: Not Found'>")
exc = exceptions.NotFound('Not There')
self.assert_equal(text_type(exc), '404: Not Found')
self.assert_equal(repr(exc), "<NotFound '404: Not Found'>")
示例4: _url_encode_impl
def _url_encode_impl(obj, charset, encode_keys, sort, key):
iterable = iter_multi_items(obj)
if sort:
iterable = sorted(iterable, key=key)
for key, value in iterable:
if value is None:
continue
if not isinstance(key, bytes):
key = text_type(key).encode(charset)
if not isinstance(value, bytes):
value = text_type(value).encode(charset)
yield url_quote(key) + '=' + url_quote_plus(value)
示例5: test_exception_repr
def test_exception_repr():
exc = exceptions.NotFound()
assert text_type(exc) == (
'404 Not Found: The requested URL was not found '
'on the server. If you entered the URL manually please check your '
'spelling and try again.')
assert repr(exc) == "<NotFound '404: Not Found'>"
exc = exceptions.NotFound('Not There')
assert text_type(exc) == '404 Not Found: Not There'
assert repr(exc) == "<NotFound '404: Not Found'>"
exc = exceptions.HTTPException('An error message')
assert text_type(exc) == '??? Unknown Error: An error message'
assert repr(exc) == "<HTTPException '???: Unknown Error'>"
示例6: proxy
def proxy(*children, **arguments):
buffer = "<" + tag
for key, value in iteritems(arguments):
if value is None:
continue
if key[-1] == "_":
key = key[:-1]
if key in self._boolean_attributes:
if not value:
continue
if self._dialect == "xhtml":
value = '="' + key + '"'
else:
value = ""
else:
value = '="' + escape(value) + '"'
buffer += " " + key + value
if not children and tag in self._empty_elements:
if self._dialect == "xhtml":
buffer += " />"
else:
buffer += ">"
return buffer
buffer += ">"
children_as_string = "".join([text_type(x) for x in children if x is not None])
if children_as_string:
if tag in self._plaintext_elements:
children_as_string = escape(children_as_string)
elif tag in self._c_like_cdata and self._dialect == "xhtml":
children_as_string = "/*<![CDATA[*/" + children_as_string + "/*]]>*/"
buffer += children_as_string + "</" + tag + ">"
return buffer
示例7: __init__
def __init__(self, exc_type, exc_value, tb):
self.lineno = tb.tb_lineno
self.function_name = tb.tb_frame.f_code.co_name
self.locals = tb.tb_frame.f_locals
self.globals = tb.tb_frame.f_globals
fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
if fn[-4:] in ('.pyo', '.pyc'):
fn = fn[:-1]
# if it's a file on the file system resolve the real filename.
if os.path.isfile(fn):
fn = os.path.realpath(fn)
self.filename = to_unicode(fn, get_filesystem_encoding())
self.module = self.globals.get('__name__')
self.loader = self.globals.get('__loader__')
self.code = tb.tb_frame.f_code
# support for paste's traceback extensions
self.hide = self.locals.get('__traceback_hide__', False)
info = self.locals.get('__traceback_info__')
if info is not None:
try:
info = text_type(info)
except UnicodeError:
info = str(info).decode('utf-8', 'replace')
self.info = info
示例8: test_exception_repr
def test_exception_repr():
exc = exceptions.NotFound()
assert text_type(exc) == (
"404 Not Found: The requested URL was not found on the server."
" If you entered the URL manually please check your spelling"
" and try again."
)
assert repr(exc) == "<NotFound '404: Not Found'>"
exc = exceptions.NotFound("Not There")
assert text_type(exc) == "404 Not Found: Not There"
assert repr(exc) == "<NotFound '404: Not Found'>"
exc = exceptions.HTTPException("An error message")
assert text_type(exc) == "??? Unknown Error: An error message"
assert repr(exc) == "<HTTPException '???: Unknown Error'>"
示例9: get_body
def get_body(self, environ=None):
return text_type(json.dumps(dict(
msg=self.error,
code=self.error_code,
request=request.method+' '+self.get_url_no_param()
)))
示例10: build_artifact
def build_artifact(self, artifact):
ctx = get_ctx()
feed_source = self.source
page = feed_source.parent
feed = AtomFeed(
title=page.record_label + u' — Pallets Project',
feed_url=url_to(feed_source, external=True),
url=url_to('/blog', external=True),
id=get_id(ctx.env.project.id)
)
for item in page.children.order_by(
'-pub_date', '-pub_order', 'title'
).limit(10):
item_author = item['author']
feed.add(
item['title'],
text_type(item['body']),
xml_base=url_to(item, external=True),
url=url_to(item, external=True),
content_type='html',
id=get_id(u'%s/%s' % (
ctx.env.project.id,
item['_path'].encode('utf-8'))),
author=item_author,
updated=datetime(*item['pub_date'].timetuple()[:3]))
with artifact.open('wb') as f:
f.write(feed.to_string().encode('utf-8'))
示例11: url_quote
def url_quote(string, charset='utf-8', errors='strict', safe='/:', unsafe=''):
"""URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.
:param unsafe: an optional sequence of unsafe characters.
.. versionadded:: 0.9.2
The `unsafe` parameter was added.
"""
if not isinstance(string, (text_type, bytes, bytearray)):
string = text_type(string)
if isinstance(string, text_type):
string = string.encode(charset, errors)
if isinstance(safe, text_type):
safe = safe.encode(charset, errors)
if isinstance(unsafe, text_type):
unsafe = unsafe.encode(charset, errors)
safe = frozenset(bytearray(safe) + _always_safe) - frozenset(bytearray(unsafe))
rv = bytearray()
for char in bytearray(string):
if char in safe:
rv.append(char)
else:
rv.extend(('%%%02X' % char).encode('ascii'))
return to_native(bytes(rv))
示例12: safe_str_cmp
def safe_str_cmp(a, b):
"""This function compares strings in somewhat constant time. This
requires that the length of at least one string is known in advance.
Returns `True` if the two strings are equal, or `False` if they are not.
.. versionadded:: 0.7
"""
if _builtin_safe_str_cmp is not None:
return _builtin_safe_str_cmp(text_type(a), text_type(b))
# Python2's version of that code dies when one is Unicode and the other is not
if len(a) != len(b):
return False
rv = 0
if isinstance(a, bytes) and isinstance(b, bytes) and not PY2:
for x, y in izip(a, b):
rv |= x ^ y
else:
for x, y in izip(a, b):
rv |= ord(x) ^ ord(y)
return rv == 0
示例13: get_body
def get_body(self, environ=None):
"""Get the HTML body."""
return text_type((
u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
u'<title>%(code)s %(name)s</title>\n'
u'<h1>%(name)s</h1>\n'
u'%(description)s\n'
) % {
'code': self.code,
'name': escape(self.name),
'description': self.get_description(environ)
})
示例14: get_body
def get_body(self, environ=None):
"""Get the XML body."""
return text_type((
u'<?xml version="1.0" encoding="UTF-8"?>\n'
u'<ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/ows/1.1 ../../../ows/1.1.0/owsExceptionReport.xsd" version="1.0.0">'
u'<ows:Exception exceptionCode="%(name)s">'
u'%(description)s'
u'</ows:Exception>'
u'</ows:ExceptionReport>'
) % {
'name': escape(self.name),
'description': self.get_description(environ)
})
示例15: escape
def escape(s, quote=None):
"""Replace special characters "&", "<", ">" and (") to HTML-safe sequences.
There is a special handling for `None` which escapes to an empty string.
.. versionchanged:: 0.9
`quote` is now implicitly on.
:param s: the string to escape.
:param quote: ignored.
"""
if s is None:
return ""
elif hasattr(s, "__html__"):
return text_type(s.__html__())
elif not isinstance(s, string_types):
s = text_type(s)
if quote is not None:
from warnings import warn
warn(DeprecationWarning("quote parameter is implicit now"), stacklevel=2)
s = s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
return s