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

Python _compat.text_type函数代码示例

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

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



在下文中一共展示了text_type函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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('&', '&amp;').replace('<', '&lt;') \
        .replace('>', '&gt;').replace('"', "&quot;")
    return s
开发者ID:gaoussoucamara,项目名称:simens-cerpad,代码行数:28,代码来源:utils.py


示例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'>"
开发者ID:2009bpy,项目名称:werkzeug,代码行数:8,代码来源:test_exceptions.py


示例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'>")
开发者ID:TheWaWaR,项目名称:werkzeug,代码行数:8,代码来源:exceptions.py


示例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)
开发者ID:08haozi,项目名称:uliweb,代码行数:12,代码来源:urls.py


示例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'>"
开发者ID:brunoais,项目名称:werkzeug,代码行数:15,代码来源:test_exceptions.py


示例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
开发者ID:211sandiego,项目名称:calllog211,代码行数:34,代码来源:utils.py


示例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
开发者ID:DancerMikerLiuNeng,项目名称:tinyFlaskwebToy,代码行数:26,代码来源:tbtools.py


示例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'>"
开发者ID:pallets,项目名称:werkzeug,代码行数:16,代码来源:test_exceptions.py


示例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()
        )))
开发者ID:hiyouth,项目名称:herovii,代码行数:7,代码来源:errors.py


示例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'))
开发者ID:Vlad-Shcherbina,项目名称:website,代码行数:31,代码来源:lektor_blog_feed.py


示例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))
开发者ID:Codefans-fan,项目名称:werkzeug,代码行数:27,代码来源:urls.py


示例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
开发者ID:smurfix,项目名称:werkzeug,代码行数:21,代码来源:security.py


示例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)
     })
开发者ID:DaTrollMon,项目名称:werkzeug,代码行数:12,代码来源:exceptions.py


示例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)
     })
开发者ID:jan-rudolf,项目名称:pywps,代码行数:13,代码来源:exceptions.py


示例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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
    return s
开发者ID:211sandiego,项目名称:calllog211,代码行数:23,代码来源:utils.py


示例16: test_sorted_url_encode

def test_sorted_url_encode():
    strict_eq(
        urls.url_encode(
            {u"a": 42, u"b": 23, 1: 1, 2: 2}, sort=True, key=lambda i: text_type(i[0])
        ),
        "1=1&2=2&a=42&b=23",
    )
    strict_eq(
        urls.url_encode(
            {u"A": 1, u"a": 2, u"B": 3, "b": 4},
            sort=True,
            key=lambda x: x[0].lower() + x[0],
        ),
        "A=1&a=2&B=3&b=4",
    )
开发者ID:pallets,项目名称:werkzeug,代码行数:15,代码来源:test_urls.py


示例17: test_etag_response_mixin_freezing

    def test_etag_response_mixin_freezing(self):
        class WithFreeze(wrappers.ETagResponseMixin, wrappers.BaseResponse):
            pass
        class WithoutFreeze(wrappers.BaseResponse, wrappers.ETagResponseMixin):
            pass

        response = WithFreeze('Hello World')
        response.freeze()
        self.assert_strict_equal(response.get_etag(),
            (text_type(wrappers.generate_etag(b'Hello World')), False))
        response = WithoutFreeze('Hello World')
        response.freeze()
        self.assert_equal(response.get_etag(), (None, None))
        response = wrappers.Response('Hello World')
        response.freeze()
        self.assert_equal(response.get_etag(), (None, None))
开发者ID:4toblerone,项目名称:werkzeug,代码行数:16,代码来源:wrappers.py


示例18: test_etag_response_mixin_freezing

def test_etag_response_mixin_freezing():
    class WithFreeze(wrappers.ETagResponseMixin, wrappers.BaseResponse):
        pass

    class WithoutFreeze(wrappers.BaseResponse, wrappers.ETagResponseMixin):
        pass

    response = WithFreeze("Hello World")
    response.freeze()
    strict_eq(response.get_etag(), (text_type(wrappers.generate_etag(b"Hello World")), False))
    response = WithoutFreeze("Hello World")
    response.freeze()
    assert response.get_etag() == (None, None)
    response = wrappers.Response("Hello World")
    response.freeze()
    assert response.get_etag() == (None, None)
开发者ID:tsampi,项目名称:tsampi-0,代码行数:16,代码来源:test_wrappers.py


示例19: get_response

 def get_response(self, environ=None):
     doc = text_type((
         u'<?xml version="1.0" encoding="UTF-8"?>\n'
         u'<!-- PyWPS %(version)s -->\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 http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd" version="1.0.0">\n'  # noqa
         u'  <ows:Exception exceptionCode="%(name)s" locator="%(locator)s" >\n'
         u'      %(description)s\n'
         u'  </ows:Exception>\n'
         u'</ows:ExceptionReport>'
     ) % {
         'version': __version__,
         'code': self.code,
         'locator': escape(self.locator),
         'name': escape(self.name),
         'description': self.get_description(environ)
     })
     return Response(doc, self.code, mimetype='text/xml')
开发者ID:jorgejesus,项目名称:PyWPS,代码行数:17,代码来源:exceptions.py


示例20: 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" locator="%(locator)s" >'
             u"%(description)s"
             u"</ows:Exception>"
             u"</ows:ExceptionReport>"
         )
         % {
             "code": self.code,
             "locator": escape(self.locator),
             "name": escape(self.name),
             "description": self.get_description(environ),
         }
     )
开发者ID:panwarnaveen9,项目名称:pywps-4,代码行数:18,代码来源:exceptions.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python _compat.to_bytes函数代码示例发布时间:2022-05-26
下一篇:
Python _compat.reraise函数代码示例发布时间: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