当前位置: 首页>>代码示例>>Python>>正文


Python utils.escape方法代码示例

本文整理汇总了Python中jinja2.utils.escape方法的典型用法代码示例。如果您正苦于以下问题:Python utils.escape方法的具体用法?Python utils.escape怎么用?Python utils.escape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jinja2.utils的用法示例。


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

示例1: format_message_cheer

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def format_message_cheer(message, cheer=False):
	if not cheer:
		return urlize(message)
	else:
		re_cheer, cheermotes = await get_cheermotes_data()
		bits = []
		splits = re_cheer.split(message)
		for i in range(0, len(splits), 4):
			bits.append(urlize(splits[i]))
			if i + 1 < len(splits):
				cheermote = cheermotes[splits[i + 2].lower()]
				codeprefix = splits[i + 1]
				count = int(splits[i + 3])
				for tier in cheermote['tiers']:
					if tier['level'] <= count:
						break
				bits.append('<span class="cheer" style="color: %s"><img src="%s" alt="%s" title="%s %d">%d</span>' % (escape(tier['color']), escape(tier['image']), escape(codeprefix), escape(cheermote['prefix']), count, count))
		return ''.join(bits) 
开发者ID:mrphlip,项目名称:lrrbot,代码行数:20,代码来源:chatlog.py

示例2: get_cheermotes_data

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def get_cheermotes_data():
	# see: https://discuss.dev.twitch.tv/t/any-update-on-the-cheermotes-docs/9123
	headers = {
		'Client-ID': config['twitch_clientid'],
		'Accept': 'application/vnd.twitchtv.v5+json',
	}
	data = await common.http.request_coro("https://api.twitch.tv/kraken/bits/actions", headers=headers)
	data = json.loads(data)
	cheermotes = {
		action['prefix'].lower(): {
			'prefix': action['prefix'],  # the original capitalisation
			'tiers': [
				{
					'color': tier['color'],
					'level': tier['min_bits'],
					'image': tier['images']['light']['static']['1'],
				}
				for tier in sorted(action['tiers'], key=lambda tier:tier['min_bits'], reverse=True)
			],
		}
		for action in data['actions']
	}
	re_cheer = r"(?:^|(?<=\s))((%s)0*)([1-9][0-9]*)(?:$|(?=\s))" % "|".join(re.escape(i) for i in cheermotes.keys())
	re_cheer = re.compile(re_cheer, re.IGNORECASE)
	return re_cheer, cheermotes 
开发者ID:mrphlip,项目名称:lrrbot,代码行数:27,代码来源:chatlog.py

示例3: _send_mail

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def _send_mail(self, maybe_mistake=False):
        """
        Send mail
        :return: boolean
        """
        if len(self.content) == 0:
            logger.info('none content for send mail')
            return True
        if maybe_mistake:
            title = '〔GSIL〕MB_MT '
        else:
            title = '〔GSIL〕'
        subject = '{title}[{types}] [{rule_name}] {count}'.format(title=title, types=self.rule_object.types, rule_name=self.rule_object.corp, count=len(self.content))
        to = get('mail', 'to')
        cc = get('mail', 'cc')
        html = '<h3>Rule: {rule_regex} Count: {count} Datetime: {datetime}</h3>'.format(rule_regex=self.rule_object.keyword, datetime=time.strftime("%Y-%m-%d %H:%M:%S"), count=len(self.content))
        for i, v in self.content.items():
            html += '<h3>({i})<a href="{url}">{hash}</a> {repository}/{path}</h3>'.format(i=i, url=v['url'], hash=v['hash'][:6], repository=v['repository'], path=v['path'])
            if len(v['match_codes']) > 0:
                code = ''
                for c in v['match_codes']:
                    code += '{c}<br>'.format(c=utils.escape(c))
                html += '<code>{code}</code><hr>'.format(code=code)
            self._save_file(v['hash'], v['code'])
        html += '</table></body>'
        return Notification(subject, to, cc).notification(html) 
开发者ID:FeeiCN,项目名称:GSIL,代码行数:28,代码来源:process.py

示例4: format_message_emoteset

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def format_message_emoteset(message, emotes, cheer=False):
	ret = ""
	stack = [(message, "")]
	while len(stack) != 0:
		prefix, suffix = stack.pop()
		for emote in emotes:
			parts = emote["regex"].split(prefix, 1)
			if len(parts) >= 3:
				stack.append((parts[-1], suffix))
				stack.append((parts[0], Markup(emote["html"].format(escape(parts[1])))))
				break
		else:
			ret += Markup(await format_message_cheer(prefix, cheer=cheer)) + suffix
	return ret 
开发者ID:mrphlip,项目名称:lrrbot,代码行数:16,代码来源:chatlog.py

示例5: format_message_explicit_emotes

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def format_message_explicit_emotes(message, emotes, size="1", cheer=False):
	if not emotes:
		return Markup(await format_message_cheer(message, cheer=cheer))

	# emotes format is
	# <emoteid>:<start>-<end>[,<start>-<end>,...][/<emoteid>:<start>-<end>,.../...]
	# eg:
	# 123:0-2/456:3-6,7-10
	# means that chars 0-2 (inclusive, 0-based) are emote 123,
	# and chars 3-6 and 7-10 are two copies of emote 456
	parsed_emotes = []
	for emote in emotes.split('/'):
		emoteid, positions = emote.split(':')
		for position in positions.split(','):
			start, end = position.split('-')
			start = int(start)
			end = int(end) + 1 # make it left-inclusive, to be more consistent with how Python does things
			parsed_emotes.append((start, end, emoteid))
	parsed_emotes.sort(key=lambda x:x[0])

	bits = []
	prev = 0
	for start, end, emoteid in parsed_emotes:
		if prev < start:
			bits.append(await format_message_cheer(message[prev:start], cheer=cheer))
		url = escape("https://static-cdn.jtvnw.net/emoticons/v1/%s/%s.0" % (
			urllib.parse.quote(emoteid), size))
		command = escape(message[start:end])
		bits.append('<img src="%s" alt="%s" title="%s">' % (url, command, command))
		prev = end
	if prev < len(message):
		bits.append(await format_message_cheer(message[prev:], cheer=cheer))
	return Markup(''.join(bits)) 
开发者ID:mrphlip,项目名称:lrrbot,代码行数:35,代码来源:chatlog.py

示例6: test_advisory_published_content_not_overescaped

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def test_advisory_published_content_not_overescaped(db, client, patch_get):
    resp = client.get(url_for('tracker.show_advisory', advisory_id=DEFAULT_ADVISORY_ID), follow_redirects=True)
    assert 200 == resp.status_code
    data = resp.data.decode()
    assert str(escape('<a href>')) not in data 
开发者ID:archlinux,项目名称:arch-security-tracker,代码行数:7,代码来源:test_advisory.py

示例7: test_advisory_generated_content_not_over_escaped

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def test_advisory_generated_content_not_over_escaped(db, client):
    resp = client.get(url_for('tracker.show_generated_advisory', advisory_id=DEFAULT_ADVISORY_ID), follow_redirects=True)
    assert 200 == resp.status_code
    data = resp.data.decode()
    assert str(escape('<a href')) not in data 
开发者ID:archlinux,项目名称:arch-security-tracker,代码行数:7,代码来源:test_advisory.py

示例8: test_advisory_published_content_not_over_escaped

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def test_advisory_published_content_not_over_escaped(db, client, patch_get):
    resp = client.post(url_for('tracker.publish_advisory', asa=DEFAULT_ADVISORY_ID), follow_redirects=True,
                       data=dict(reference=f'https://security.archlinux.org/{DEFAULT_ADVISORY_ID}', confirm=True))
    assert 200 == resp.status_code
    assert 'Published {}'.format(DEFAULT_ADVISORY_ID) in resp.data.decode()

    resp = client.get(url_for('tracker.show_advisory', advisory_id=DEFAULT_ADVISORY_ID), follow_redirects=True)
    assert 200 == resp.status_code
    data = resp.data.decode()
    assert str(escape('<a href')) not in data 
开发者ID:archlinux,项目名称:arch-security-tracker,代码行数:12,代码来源:test_advisory.py

示例9: urlize

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def urlize(ctx, text, trim_url_limit=None, rel=None, target=None):
    """Converts any URLs in text into clickable links. Works on http://,
    https:// and www. links. Links can have trailing punctuation (periods,
    commas, close-parens) and leading punctuation (opening parens) and
    it'll still do the right thing.
    Aditionally it will populate the input with application context related
    links linke issues and groups.

    If trim_url_limit is not None, the URLs in link text will be limited
    to trim_url_limit characters.

    If nofollow is True, the URLs in link text will get a rel="nofollow"
    attribute.

    If target is not None, a target attribute will be added to the link.
    """

    words = _word_split_re.split(escape(text))
    for i, word in enumerate(words):
        match = _punctuation_re.match(word)
        if match:
            lead, word, trail = match.groups()
            word = sub('({})'.format(cve_id_regex), '<a href="/\\1" rel="noopener">\\1</a>', word)
            word = sub('({})'.format(vulnerability_group_regex), '<a href="/\\1" rel="noopener">\\1</a>', word)
            words[i] = '{}{}{}'.format(lead, word, trail)

    text = ''.join(words)
    if ctx.autoescape:
        text = Markup(text)

    text = do_urlize(ctx, text, trim_url_limit=trim_url_limit, target=target, rel=rel)
    return text 
开发者ID:archlinux,项目名称:arch-security-tracker,代码行数:34,代码来源:blueprint.py

示例10: advisory_escape_html

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def advisory_escape_html(advisory):
    start = '\nWorkaround\n==========\n\n'
    end = '\n\nReferences\n==========\n\n'
    if start not in advisory or end not in advisory:
        return None
    start_index = advisory.index(start) + len(start)
    end_index = advisory.index(end)
    advisory = advisory[:start_index] + str(html_escape(advisory[start_index:end_index])) + advisory[end_index:]
    return advisory 
开发者ID:archlinux,项目名称:arch-security-tracker,代码行数:11,代码来源:advisory.py

示例11: empty_and_escape

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def empty_and_escape(value):
    ''' returns '' for a None value else escapes the content useful for form
    elements. '''
    if value is None:
        return ''
    else:
        return escape(value) 
开发者ID:italia,项目名称:daf-recipes,代码行数:9,代码来源:jinja_extensions.py

示例12: test_markup_leaks

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def test_markup_leaks(self):
        counts = set()
        for count in range(20):
            for item in range(1000):
                escape("foo")
                escape("<foo>")
                escape(u"foo")
                escape(u"<foo>")
            counts.add(len(gc.get_objects()))
        assert len(counts) == 1, 'ouch, c extension seems to leak objects' 
开发者ID:chalasr,项目名称:Flask-P2P,代码行数:12,代码来源:utils.py

示例13: suite

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(LRUCacheTestCase))
    suite.addTest(unittest.makeSuite(HelpersTestCase))

    # this test only tests the c extension
    if not hasattr(escape, 'func_code'):
        suite.addTest(unittest.makeSuite(MarkupLeakTestCase))

    return suite 
开发者ID:chalasr,项目名称:Flask-P2P,代码行数:12,代码来源:utils.py

示例14: build_message_html

# 需要导入模块: from jinja2 import utils [as 别名]
# 或者: from jinja2.utils import escape [as 别名]
def build_message_html(time, source, target, message, specialuser, usercolor, emoteset, emotes, displayname):
	if source.lower() == config['notifyuser']:
		return '<div class="notification line" data-timestamp="%d">%s</div>' % (time.timestamp(), escape(message))

	if message[:4].lower() in (".me ", "/me "):
		is_action = True
		message = message[4:]
	else:
		is_action = False

	ret = []
	ret.append('<div class="line" data-timestamp="%d">' % time.timestamp())
	if 'staff' in specialuser:
		ret.append('<span class="badge staff"></span> ')
	if 'admin' in specialuser:
		ret.append('<span class="badge admin"></span> ')
	if "#" + source.lower() == target.lower():
		ret.append('<span class="badge broadcaster"></span> ')
	if 'mod' in specialuser:
		ret.append('<span class="badge mod"></span> ')
	if 'turbo' in specialuser:
		ret.append('<span class="badge turbo"></span> ')
	if 'subscriber' in specialuser:
		ret.append('<span class="badge subscriber"></span> ')
	ret.append('<span class="nick"')
	if usercolor:
		ret.append(' style="color:%s"' % escape(usercolor))
	ret.append('>%s</span>' % escape(displayname or get_display_name(source)))

	if is_action:
		ret.append(' <span class="action"')
		if usercolor:
			ret.append(' style="color:%s"' % escape(usercolor))
		ret.append('>')
	else:
		ret.append(": ")

	if 'cleared' in specialuser:
		ret.append('<span class="deleted">&lt;message deleted&gt;</span>')
		# Use escape() rather than urlize() so as not to have live spam links
		# either for users to accidentally click, or for Google to see
		ret.append('<span class="message cleared">%s</span>' % escape(message))
	else:
		messagehtml = await format_message(message, emotes, emoteset, cheer='cheer' in specialuser)
		ret.append('<span class="message">%s</span>' % messagehtml)

	if is_action:
		ret.append('</span>')
	ret.append('</div>')
	return ''.join(ret) 
开发者ID:mrphlip,项目名称:lrrbot,代码行数:52,代码来源:chatlog.py


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