Python html 模块,escape() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用html.escape()。
def format(self, content: Optional[QqTag],
blanks_to_pars=True,
keep_end_pars=True) -> str:
"""
:param content: Could be QqTag or any iterable of QqTags
:param blanks_to_pars: use blanks_to_pars (True or False)
:param keep_end_pars: keep end paragraphs
:return: str: text of tag
"""
if content is None:
return ""
out = []
for child in content:
if isinstance(child, str):
if blanks_to_pars:
out.append(self.blanks_to_pars(html_escape(
child, keep_end_pars)))
else:
out.append(html_escape(child))
else:
out.append(self.handle(child))
return "".join(out)
def _signatures_make_html(content):
"""
Create part with Signatures
"""
html = "<div>"
decode_content = json.loads(content)
severity = int(decode_content['severity'])
if severity <= 1:
flag = "info"
elif severity <= 4:
flag = "warning"
else:
flag = "important"
html += (
"<label class=\"label label-{}\">{} ({})</label> <pre>{}</pre>"
).format(flag, escape(decode_content['name']),
escape(str(severity)),
escape(decode_content['description']))
html += "</div>"
return html
def html_report(content):
html = "<div>"
html_parts = dict()
for item in content:
if item.name == "code_header" or item.name == "code_body" and item.option not in html_parts:
html_parts[item.option] = {'header': None, 'body': None}
if item.name == "code_header":
html_parts[item.option]['header'] = "<label class=\"label label-info\">Code Header</label> <pre>{}</pre>".format(escape(base64.b64decode(item.content).decode('utf-8')))
elif item.name == "code_body":
html_parts[item.option]['body'] = "<label class=\"label label-info\">Code Body</label> <pre>{}</pre>".format(escape(base64.b64decode(item.content).decode('utf-8')))
elif item.name == "error":
html += "<label class=\"label label-inverse\">Error</label> <pre>{}</pre>".format(escape(base64.b64decode(item.content).decode('utf-8')))
else:
html += "LAMA PARSE ERROR<br/>"
for i in sorted(html_parts):
html += "<h6>Script " + i + "</h6>"
if html_parts[i]['header']:
html += html_parts[i]['header']
if html_parts[i]['body']:
html += html_parts[i]['body']
html += "</div>"
return html
def _signatures_make_html(content):
"""
Create part with Signatures
"""
html = "<div>"
decode_content = json.loads(content)
severity = int(decode_content['severity'])
if severity <= 1:
flag = "info"
elif severity <= 4:
flag = "warning"
else:
flag = "important"
html += (
"<label class=\"label label-{}\">{} ({})</label> <pre>{}</pre>"
).format(flag,
escape(decode_content['description']))
html += "</div>"
return html
def handle_starttag(self, tag, attrs):
if self.hide_output:
return
if self.tag_count != 0 and tag != "img": # img is always self-closed
self.tag_count += 1
if tag in SUPPORTED_TAGS and (self.tag_count == 0):
self.push_tag("<"+tag+">")
self.current_tag = tag
elif tag == "a" and (self.tag_count == 0):
href = find_href(attrs)
if href:
self.push_tag("<a href='{0}'>".format(html.escape(href, quote=True)))
self.current_tag = "a"
elif tag in ('p', 'br', 'div', 'table', 'dt', 'dd', 'li', 'tr'):
self.push_newlines(2)
elif tag == 'td':
self.push_newlines(1)
elif tag in ('script', 'style'):
self.hide_output = True
def SyncRadioStation(self):
radioURI = html.escape(self.CurrentURI) #escape the uri for &
LogMessage("Current radio URI: " + radioURI)
radioStationFound = False
for k,v in self.radioFavorites.items():
if radioURI == html.escape(v): #if CurrentURI is found in the values of the radio favorites dict
LogMessage('Radio station found in favorites list,updating radio switch selector')
dictOptions = Devices[4].Options
listLevelNames = dictOptions['LevelNames'].split('|')
radioLevel = (listLevelNames.index(k))*10 #get the index and multiply it with 10 to get the level of selector switch
self.sonosRadio = radioLevel
UpdateDevice(4, 1, str(self.sonosRadio))
radioStationFound = True
###self.SyncDevices()
if radioStationFound == False:
LogMessage('Radio station not found in favorites list,updating radio switch selector')
self.sonosRadio = 0
UpdateDevice(4, str(self.sonosRadio))
return
# Make sure that the Domoticz devices are in sync
def local_html_escape(data, quote=False):
"""
Works with bytes.
Replace special characters "&","<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default),the quotation mark
characters,both double quote (") and single quote (') characters are also
translated.
"""
if PY2:
import cgi
data = cgi.escape(data, quote)
return data.replace("'", "'") if quote else data
else:
import html
if isinstance(data, str):
return html.escape(data, quote=quote)
data = data.replace(b"&", b"&") # Must be done first!
data = data.replace(b"<", b"<")
data = data.replace(b">", b">")
if quote:
data = data.replace(b'"', b""")
data = data.replace(b'\'', b"'")
return data
def local_html_escape(data, b"&") # Must be done first!
data = data.replace(b"<", b"'")
return data
def get_cell_markup(self, x, y=None, data=None):
"""
See if a column has formatting (if x and y are supplied) or
see if a cell has formatting. If it does,return the formatted
string,otherwise return data that is escaped (if that column
has formatting),or just the plain data.
"""
if x in self._cell_markup:
if y is None:
return True # markup for this column
elif y in self._cell_markup[x]:
return self._cell_markup[x][y]
else:
return escape(data)
else:
if y is None:
return False # no markup for this column
else:
return data
def _parse_route_template(template, default_sufix=''):
"""Lazy route template parser."""
variables = {}
reverse_template = pattern = ''
args_count = last = 0
for match in _route_re.finditer(template):
part = template[last:match.start()]
name = match.group(1)
expr = match.group(2) or default_sufix
last = match.end()
if not name:
name = '__%d__' % args_count
args_count += 1
pattern += '%s(?P<%s>%s)' % (re.escape(part), name, expr)
reverse_template += '%s%%(%s)s' % (part, name)
variables[name] = re.compile('^%s$' % expr)
part = template[last:]
kwargs_count = len(variables) - args_count
reverse_template += part
regex = re.compile('^%s%s$' % (pattern, re.escape(part)))
return regex, reverse_template, args_count, kwargs_count, variables
def update_service_account_info():
if current_user.is_white_team or current_user.is_blue_team:
if 'name' in request.form and 'value' in request.form and 'pk' in request.form:
account = session.query(Account).get(int(request.form['pk']))
if current_user.team == account.service.team:
if account:
if request.form['name'] == 'username':
account.username = html.escape(request.form['value'])
elif request.form['name'] == 'password':
account.password = html.escape(request.form['value'])
session.add(account)
session.commit()
return jsonify({'status': 'Updated Account information'})
return jsonify({'error': 'Incorrect permissions'})
return jsonify({'error': 'Incorrect permissions'})
return jsonify({'error': 'Incorrect permissions'})
def admin_update_password():
if current_user.is_white_team:
if 'user_id' in request.form and 'password' in request.form:
try:
user_obj = session.query(User).filter(User.id == request.form['user_id']).one()
except noresultFound:
return redirect(url_for('auth.login'))
user_obj.update_password(html.escape(request.form['password']))
user_obj.authenticated = False
session.add(user_obj)
session.commit()
flash('Password Successfully Updated.', 'success')
return redirect(url_for('admin.manage'))
else:
flash('Error: user_id or password not specified.', 'danger')
return redirect(url_for('admin.manage'))
else:
return {'status': 'Unauthorized'}, 403
def admin_add_user():
if current_user.is_white_team:
if 'username' in request.form and 'password' in request.form and 'team_id' in request.form:
team_obj = session.query(Team).filter(Team.id == request.form['team_id']).one()
user_obj = User(username=html.escape(request.form['username']),
password=html.escape(request.form['password']),
team=team_obj)
session.add(user_obj)
session.commit()
flash('User successfully added.', 'success')
return redirect(url_for('admin.manage'))
else:
flash('Error: Username,Password,or Team ID not specified.', 403
def escape(self, tags):
output = []
for tag in tags:
if re.match(r'<.+ >$', tag):
try:
etree.fromstring(tag)
output.append(tag)
except:
tag = re.sub(r'(<)(.+) (>)', r'\1\n\2\n\3', tag)
tag = self.tagger.tag_text(tag, notagdns=True, notagip=True, notagurl=True, notagemail=True, tagonly=True)
tag = [html.escape(t) for t in tag]
output += tag
elif not re.match(r'<.+>$', tag):
output.append(html.escape(tag))
else:
test = re.match(r'<rep(.+?) text="(.+)"', tag)
if test is not None:
output.append('<rep{} text="{}"/>'.format(test.group(1), html.escape(test.group(2))))
else:
if re.match(r'[<>]\t', tag):
output.append(html.escape(tag))
else:
output.append(tag)
return output
def segment_to_html(segment):
"""Create simple HTML from ChatMessageSegment"""
text = html.escape(segment.text) if segment.text else ""
text = text.replace('\n', '<br>\n')
message = []
if segment.type_ == hangups.hangouts_pb2.SEGMENT_TYPE_TEXT:
message.append(text)
elif segment.type_ == hangups.hangouts_pb2.SEGMENT_TYPE_LINK:
message.append(
'<a href="{}">{}</a>'.format(segment.link_target if segment.link_target else text, text)
)
elif segment.type_ == hangups.hangouts_pb2.SEGMENT_TYPE_LINE_BREAK:
message.append('<br />\n')
else:
logging.warning('Ignoring unkNown chat message segment type: {}'.format(segment.type_))
if not segment.type_ == hangups.hangouts_pb2.SEGMENT_TYPE_LINE_BREAK:
for is_f, f in ((segment.is_bold, 'b'), (segment.is_italic, 'i'),
(segment.is_strikethrough, 's'), (segment.is_underline, 'u')):
if is_f:
message.insert(0, '<{}>'.format(f))
message.append('</{}>'.format(f))
return ''.join(message)
def _escape_text(self, s):
"""Escape text
In addition to escaping text,unicode characters are replaced with a
span that will display the glyph using CSS. This is to ensure that the
text has a consistent width.
"""
tpl = ('<span class="u"><span class="g">&#x{0:x};</span>'
'<span class="ns">{1}</span></span>')
out = ''
for c in s:
w = utils.str_width(c)
if unicodedata.category(c) in ('Co', 'Cn', 'So'):
out += tpl.format(ord(c), ' ')
elif w > 1 or ord(c) > 255:
out += tpl.format(ord(c), ' ' * w)
else:
out += escape(c)
return out
def _iter_child_renders(self, pretty=False):
for child in self.childs:
if not issubclass(child.__class__, DOMElement):
tempyREPR_cls = self._search_for_view(child)
if tempyREPR_cls:
# If there is a TempyREPR class defined in the child class we make a DOMElement out of it
# this trick is used to avoid circular imports
class Patched(tempyREPR_cls, DOMElement):
pass
child = Patched(child)
try:
yield child.render(pretty=pretty)
except (AttributeError, NotImplementedError):
if isinstance(child, Escaped):
yield child._render
else:
yield html.escape(str(child))
except Exception as ex:
raise ex
def _change_flowBox_font(self):
'''
Update the font and fontsize used in the current content
of the flowBox.
'''
for flowBox_child in self._flowBox.get_children():
label = flowBox_child.get_child().get_child()
text = label.get_label()
(emoji, name) = self._parse_emoji_and_name_from_text(text)
if emoji:
new_text = (
'<span font="%s %s" fallback="%s">'
%(self._font, self._fontsize, str(self._fallback).lower())
+ html.escape(emoji)
+ '</span>')
if name:
new_text += (
'<span fallback="false" font="%s">'
%(self._fontsize / 2)
+ html.escape(name)
+ '</span>')
label.set_text(new_text)
label.set_use_markup(True)
self.show_all()
self._busy_stop()
def escape_html(s, quote=True):
"""
Replace special characters "&","<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default),both double quote (") and single quote (') characters are also
translated.
If a `HTMLString` is provied,it's assumed that whatever you give to
escape_html is a string with any unsafe values already escaped.
"""
if hasattr(s, '__html__'):
s = s.__html__()
else:
s = escape(text_type(s), quote=quote)
return s
def local_html_escape(data, b"'")
return data
def add_comment(request, post_id):
if request.method == 'GET':
post = Post.objects.get(pk=post_id)
form = CommentForm({'post_id':post.id, 'code':post.code})
return render(request, 'add_comment_form.html', {'post': post, 'form':form})
else:
form = CommentForm(request.POST or None)
if form.is_valid():
Comment.objects.create(
code=html.escape(form.cleaned_data['code']),
description=html.escape(form.cleaned_data['description']),
post=Post.objects.get(pk=form.cleaned_data['post_id']),
author=request.user
)
return redirect('/post/{}'.format(form.cleaned_data['post_id']), permanent=False)
post = Post.objects.get(pk=form.cleaned_data['post_id'])
return render(request, 'form':form})
def response_text(self, content, escape=False):
"""
????? content ?????????????????
:param content: ????
:param escape: ????????? (?????)
:return: ?????????? XML ????
"""
self._check_parse()
content = self._transcoding(content)
if escape:
if six.PY2:
content = cgi.escape(content)
else:
import html
content = html.escape(content)
response = TextReply(message=self.__message, content=content).render()
return self._encrypt_response(response)
def _html(self, deFinition):
"""Generate documentation string in HTML format
"""
if sys.version_info >= (3, 4):
escaped_doc = html.escape(
html.unescape(deFinition.doc), quote=False)
else:
try:
escaped_doc = cgi.escape(
HTMLParser.unescape.__func__(
HTMLParser, deFinition.doc.encode('utf8')
)
)
except AttributeError:
# Python 3.x < 3.4
escaped_doc = cgi.escape(
HTMLParser.unescape(HTMLParser, deFinition.doc)
)
escaped_doc = escaped_doc.replace('\n', '<br>')
return '{0}\n{1}'.format(deFinition.full_name, escaped_doc)
def __str__(self):
reported_count = len(self.reported_by)
reported_list = ','.join(
[str(reporter) for reporter in self.reported_by][:3]) + (
' and %d others' % (reported_count - 3)
if reported_count > 3
else '')
params = {
'id': self.id,
'phone_nr': self.phone_nr,
'account_nr': self.account_nr,
'bank_name': self.bank_name,
'remark': self.remark,
'reported_by': reported_list,
'added_by': self.added_by
}
s = ("<b>Verified Member: C#{id}</b>\n"
"<b>Cellular:</b> {phone_nr}\n"
"Telegram ID: {account_nr}\n"
"Name: {bank_name}\n"
"DNA: {remark}\n"
"Voted by: {reported_by}\n").format(
**{k: escape_html(str(v)) for (k, v) in params.items()}
)
print(s)
return s
def sanitize(text):
"""Gets rid of < and > and & and,for good measure,:"""
return html.escape(text, quote=True).replace(':', ':')
def text(self, value):
self._text = html.escape(value)
if self.view and self.view.is_loaded:
self.view.dispatch({'name': 'text', 'selector': '#' + self.id, 'text': value})
def on_view_attached(self):
super(TextBox, self).on_view_attached()
def text_changed_callback(event, interface):
self._text = html.escape(event['event_object']['target']['value'])
self.view.on('change', text_changed_callback, '#' + self.id)
def _list2table(lst, escape=True):
"""Turn a list into an HTML table (to be used as a DOT label)."""
table = '<<table border="0" cellborder="0">{}</table>>' # table HTML format
row = '<tr><td align="center">{}</td></tr>' # row HTML format
escape_function = html.escape if escape else lambda x: x
return table.format("\n".join(map(row.format, map(lambda x: escape_function(str(x)), lst or [""]))))
def _render(self, cfg):
for node in cfg.nodes.values():
fillcolor = self._node_color(node, cfg)
if isinstance(node, (Basic, Loop)):
stmt = '<font color="#ffffff" point-size="11">{} </font>'
stmts = map(lambda x: stmt.format(html.escape(str(x))), node.stmts)
label = self._list2table(list(stmts), escape=False)
else:
label = self._escape_label(self._shorten_label(str(node)))
self._render_node(node, label, fillcolor)
self._render_edges(cfg)
def _basic_node_label(self, node, result):
state = '<font point-size="9">{} </font>'
states = map(lambda x: state.format(html.escape(str(x)).replace('\n', '<br />')), result.get_node_result(node))
stmt = '<font color="#ffffff" point-size="11">{}</font>'
stmts = map(lambda x: stmt.format(html.escape(str(x))), node.stmts)
node_result = [item for items in zip_longest(states, stmts) for item in items if item is not None]
return self._list2table(node_result, escape=False)
def html_report(content):
html = "<div>"
for item in content:
if item.name == "key1":
html += "Key1 : {}".format(escape(item.content))
else:
# Error
pass
html += "</div>"
return html
def html_report(content):
html = "<div>"
for item in content:
if item.name == "name1":
html += "Name1 : {}".format(escape(item.content))
else:
# Error
pass
html += "</div>"
return html
def _make_menu_malware(m, level=0, actif=""):
html = ""
tab = ""
if level:
tab = level * 4 * " " + level * "-" + " "
html += "<li id=\"menu_malware_{}\" class=\"menu_malware {}\"><a href=\"#\" onclick=\"show_malware({})\">{}{}</a></li>".format(str(m.uid), actif, str(m.uid), tab, escape(m.name))
if len(m.extract_malware):
html += "<ul class=\"nav nav-list\">"
for m_e in m.extract_malware:
html += HtmlReporter._make_menu_malware(m_e, level+1)
html += "</ul>"
return html
html += "{}".format([me.name for me in m.extract_malware])
def _make_module_menu(malware):
html = ""
html += "<div>"
html += "<ul class=\"nav nav-pills modules-pills\">"
for i, m in enumerate(malware.module_status):
module_class = Module.get_module_by_name(m.module_cls_name)
module_name = module_class.module_name()
active = ""
if i is 0:
active = "active"
html += "<li id=\"menu_module_malware_{}_{}\" class=\"menu_module_malware menu_module_malware_{} {}\"><a href=\"#\" onclick=\"show_module_malware({},{})\">{}</a></li>".format(str(malware.uid),str(m.id),str(malware.uid),active,escape(module_name))
html += "</ul>"
html += "</div>"
return html
def _make_indicator_report(module_cls_name, indicators):
module_class = Module.get_module_by_name(module_cls_name)
html_report_fct = getattr(module_class, "html_report", None)
html = ""
if callable(html_report_fct):
html += html_report_fct(indicators)
else:
for indic in indicators:
html += "<div><b>{} ({}): </b>{}<br/></div>".format(escape(indic.name),
indic.score,
escape(indic.content))
return html
def html_report(content):
html = "<div>"
for item in content:
if item.name == "code":
html += "<label class=\"label label-info\">Code</label> <pre>{}</pre>".format(escape(base64.b64decode(item.content).decode('utf-8')))
elif item.name == "error":
html += "<label class=\"label label-inverse\">Error</label> <pre>{}</pre>".format(escape(base64.b64decode(item.content).decode('utf-8')))
else:
html += "LAMA PARSE ERROR"
html += "</div>"
return html
def _category_make_html(content):
"""
Create part with categorie
"""
html = "<div>"
html += "<b>Category : </b>{}".format(escape(content))
html += "</div>"
return html
def _buff_yara_make_html(content):
"""
Create part with Yara results
"""
decode_content = json.loads(content)
html = "<div>"
for cont in decode_content:
html += (
"<label class=\"label label-info\">{}</label> : strings {}"
).format(escape(cont['name']),
escape(",".join(cont['strings'])))
html += "<br/>{}".format(cont['Meta']['description'])
html += "</div>"
return html
def html_report(content):
html = "<div>"
html_type = {'important': "",
'warning': "",
'info': "",
'inverse': ""}
for item in content:
if item.name == "analysis":
decoded_content = json.loads(item.content)
score = item.score
if score >= 5:
type_label = "important"
elif score >= 2:
type_label = "warning"
elif score > 0:
type_label = "info"
else:
type_label = "inverse"
html_type[type_label] += "<label class=\"label label-{}\">{}</label> -> <b>{}</b><pre>{}</pre>".format(
type_label,
escape(decoded_content["type"]),
escape(decoded_content["keyword"]),
escape(decoded_content["description"])
)
elif item.name == 'macros':
decoded_content = json.loads(item.content)
html += "<label class=\"label label-info\">Source</label> : <b>{}</b><pre>{}</pre>".format(escape(decoded_content['vba_filename']),
escape(decoded_content['code']))
else:
html += "LAMA PARSE ERROR"
html += html_type['important']
html += html_type['warning']
html += html_type['info']
html += html_type['inverse']
html += "</div>"
return html
def html_report(content):
html = "<div>"
for item in content:
if item.name == "error":
html += "<b>Error : </b>{}".format(escape(item.content))
else:
html += "LAMA PARSE ERROR"
html += "</div>"
return html
def html_report(content):
html = "<div>"
for item in content:
if item.name == "out":
out = base64.b64decode(item.content)
html += "<label class=\"label label-info\">out</label><pre>{}</pre>".format(escape(out.decode("utf-8")))
if item.name == "returncode":
html += "<label class=\"label label-info\">Return code : {}</label><br/>".format(escape(item.content))
html += "</div>"
return html
def html_report(content):
html = ""
html_tar = ""
html_err = ""
for item in content:
if item.name == "script":
json_decode = json.loads(item.content)
html += "<label class=\"label\">Script</label> {} <pre>{}</pre>".format(escape(json_decode['filename']), escape(base64.b64decode(json_decode['code']).decode('utf-8')))
elif item.name == "tar":
archive_name = os.path.basename(item.content)
html_tar += "<label class=\"label\">Exctact files : </label> <a href=\"/file?path={}\">{}</a><br />".format(item.content, archive_name)
else:
html_err += "LAMA PARSE ERROR"
html = "<div>{}{}{}</div>".format(html_tar, html, html_err)
return html
def _category_make_html(content):
"""
Create part with categorie
"""
html = "<div>"
html += "<b>Category : </b>{}".format(escape(content))
html += "</div>"
return html
def _buff_yara_make_html(content):
"""
Create part with Yara results
"""
decode_content = json.loads(content)
html = "<div>"
for cont in decode_content:
html += (
"<label class=\"label label-info\">{}</label> : strings {}"
).format(escape(cont['name']),".join(cont['strings'])))
html += "<br/>{}".format(cont['Meta']['description'])
html += "</div>"
return html
def render_raw_text(token):
return html.escape(token.content)
def htmlUnkNown(x):
return '<code>'+html.escape(saferepr(x))+'</code>'