本文整理汇总了Python中html.escape方法的典型用法代码示例。如果您正苦于以下问题:Python html.escape方法的具体用法?Python html.escape怎么用?Python html.escape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类html
的用法示例。
在下文中一共展示了html.escape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _as_graph
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def _as_graph(self, finals: Optional[List[str]]) -> Digraph: # pragma: no cover
if Digraph is None:
raise ImportError('The graphviz package is required to draw the graph.')
graph = Digraph()
if finals is None:
patterns = [
'{}: {} with {}'.format(
self._colored_pattern(i), html.escape(str(p.expression)), self._format_constraint_set(c)
) for i, (p, l, c) in enumerate(self.patterns)
]
graph.node('patterns', '<<b>Patterns:</b><br/>\n{}>'.format('<br/>\n'.join(patterns)), {'shape': 'box'})
self._make_graph_nodes(graph, finals)
if finals is None:
constraints = [
'{}: {} for {}'.format(self._colored_constraint(i), html.escape(str(c)), self._format_pattern_set(p))
for i, (c, p) in enumerate(self.constraints)
]
graph.node(
'constraints', '<<b>Constraints:</b><br/>\n{}>'.format('<br/>\n'.join(constraints)), {'shape': 'box'}
)
self._make_graph_edges(graph)
return graph
示例2: _make_graph_edges
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def _make_graph_edges(self, graph: Digraph) -> None: # pragma: no cover
for state in self.states:
for _, transitions in state.transitions.items():
for transition in transitions:
t_label = '<'
if transition.variable_name:
t_label += '{}: '.format(self._colored_variable(transition.variable_name))
t_label += 'ε' if transition.label is _EPS else html.escape(str(transition.label))
if is_operation(transition.label):
t_label += '('
t_label += '<br/>{}'.format(self._format_pattern_set(transition.patterns))
if transition.check_constraints is not None:
t_label += '<br/>{}'.format(self._format_constraint_set(transition.check_constraints))
if transition.subst is not None:
t_label += '<br/>{}'.format(html.escape(str(transition.subst)))
t_label += '>'
start = 'n{!s}'.format(state.number)
if state.matcher and len(state.matcher.automaton.states) > 1:
start += '-end'
end = 'n{!s}'.format(transition.target.number)
graph.edge(start, end, t_label)
示例3: get_source
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def get_source(
self,
_env: jinja2.Environment,
template: str
) -> typing.Tuple[str, str, typing.Callable[[], bool]]:
path = os.path.join(self._subdir, template)
try:
source = utils.read_file(path)
except OSError as e:
source = html_fallback.replace("%ERROR%", html.escape(str(e)))
source = source.replace("%FILE%", html.escape(template))
log.misc.exception("The {} template could not be loaded from {}"
.format(template, path))
# Currently we don't implement auto-reloading, so we always return True
# for up-to-date.
return source, path, lambda: True
示例4: format
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def format(self, record: logging.LogRecord) -> str:
record_clone = copy.copy(record)
record_clone.__dict__.update(self._colordict)
if record_clone.levelname in self._log_colors:
color = self._log_colors[record_clone.levelname]
color_str = self._colordict[color]
record_clone.log_color = color_str # type: ignore[attr-defined]
else:
record_clone.log_color = '' # type: ignore[attr-defined]
for field in ['msg', 'filename', 'funcName', 'levelname', 'module',
'name', 'pathname', 'processName', 'threadName']:
data = str(getattr(record_clone, field))
setattr(record_clone, field, pyhtml.escape(data))
msg = super().format(record_clone)
if not msg.endswith(self._colordict['reset']):
msg += self._colordict['reset']
return msg
示例5: on_proxy_authentication_required
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def on_proxy_authentication_required(self, proxy, authenticator):
"""Called when a proxy needs authentication."""
proxy_id = ProxyId(proxy.type(), proxy.hostName(), proxy.port())
if proxy_id in _proxy_auth_cache:
authinfo = _proxy_auth_cache[proxy_id]
authenticator.setUser(authinfo.user)
authenticator.setPassword(authinfo.password)
else:
msg = '<b>{}</b> says:<br/>{}'.format(
html.escape(proxy.hostName()),
html.escape(authenticator.realm()))
abort_on = self._get_abort_signals()
answer = message.ask(
title="Proxy authentication required", text=msg,
mode=usertypes.PromptMode.user_pwd, abort_on=abort_on)
if answer is not None:
authenticator.setUser(answer.user)
authenticator.setPassword(answer.password)
_proxy_auth_cache[proxy_id] = answer
示例6: authentication_required
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def authentication_required(url, authenticator, abort_on):
"""Ask a prompt for an authentication question."""
realm = authenticator.realm()
if realm:
msg = '<b>{}</b> says:<br/>{}'.format(
html.escape(url.toDisplayString()), html.escape(realm))
else:
msg = '<b>{}</b> needs authentication'.format(
html.escape(url.toDisplayString()))
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
answer = message.ask(title="Authentication required", text=msg,
mode=usertypes.PromptMode.user_pwd,
abort_on=abort_on, url=urlstr)
if answer is not None:
authenticator.setUser(answer.user)
authenticator.setPassword(answer.password)
return answer
示例7: javascript_prompt
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def javascript_prompt(url, js_msg, default, abort_on, *, escape_msg=True):
"""Display a javascript prompt."""
log.js.debug("prompt: {}".format(js_msg))
if config.val.content.javascript.modal_dialog:
raise CallSuper
if not config.val.content.javascript.prompt:
return (False, "")
js_msg = html.escape(js_msg) if escape_msg else js_msg
msg = '<b>{}</b> asks:<br/>{}'.format(html.escape(url.toDisplayString()),
js_msg)
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
answer = message.ask('Javascript prompt', msg,
mode=usertypes.PromptMode.text,
default=default,
abort_on=abort_on, url=urlstr)
if answer is None:
return (False, "")
else:
return (True, answer)
示例8: javascript_alert
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def javascript_alert(url, js_msg, abort_on, *, escape_msg=True):
"""Display a javascript alert."""
log.js.debug("alert: {}".format(js_msg))
if config.val.content.javascript.modal_dialog:
raise CallSuper
if not config.val.content.javascript.alert:
return
js_msg = html.escape(js_msg) if escape_msg else js_msg
msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()),
js_msg)
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
message.ask('Javascript alert', msg, mode=usertypes.PromptMode.alert,
abort_on=abort_on, url=urlstr)
# Needs to line up with the values allowed for the
# content.javascript.log setting.
示例9: _on_proxy_authentication_required
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def _on_proxy_authentication_required(self, url, authenticator,
proxy_host):
"""Called when a proxy needs authentication."""
msg = "<b>{}</b> requires a username and password.".format(
html_utils.escape(proxy_host))
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
answer = message.ask(
title="Proxy authentication required", text=msg,
mode=usertypes.PromptMode.user_pwd,
abort_on=[self.abort_questions], url=urlstr)
if answer is not None:
authenticator.setUser(answer.user)
authenticator.setPassword(answer.password)
else:
try:
sip.assign( # type: ignore[attr-defined]
authenticator,
QAuthenticator())
except AttributeError:
self._show_error_page(url, "Proxy authentication required")
示例10: get_filename_question
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def get_filename_question(*, suggested_filename, url, parent=None):
"""Get a Question object for a download-path.
Args:
suggested_filename: The "default"-name that is pre-entered as path.
url: The URL the download originated from.
parent: The parent of the question (a QObject).
"""
suggested_filename = utils.sanitize_filename(suggested_filename)
q = usertypes.Question(parent)
q.title = "Save file to:"
q.text = "Please enter a location for <b>{}</b>".format(
html.escape(url.toDisplayString()))
q.url = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
q.mode = usertypes.PromptMode.download
q.completed.connect(q.deleteLater)
q.default = _path_suggestion(suggested_filename)
return q
示例11: update_text
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def update_text(self, matched: str, unmatched: str) -> None:
"""Set the text for the hint.
Args:
matched: The part of the text which was typed.
unmatched: The part of the text which was not typed yet.
"""
if (config.cache['hints.uppercase'] and
self._context.hint_mode in ['letter', 'word']):
matched = html.escape(matched.upper())
unmatched = html.escape(unmatched.upper())
else:
matched = html.escape(matched)
unmatched = html.escape(unmatched)
if matched:
match_color = config.cache['colors.hints.match.fg'].name()
self.setText('<font color="{}">{}</font>{}'.format(
match_color, matched, unmatched))
else:
self.setText(unmatched)
self.adjustSize()
示例12: __init__
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def __init__(self, exc_text, text, parent=None):
super().__init__(parent)
vbox = QVBoxLayout(self)
label = QLabel("<b>There was an error while reporting the crash</b>:"
"<br/>{}<br/><br/>"
"Please copy the text below and send a mail to "
"<a href='mailto:crash@qutebrowser.org'>"
"crash@qutebrowser.org</a> - Thanks!".format(
html.escape(exc_text)))
vbox.addWidget(label)
txt = QTextEdit()
txt.setReadOnly(True)
txt.setTabChangesFocus(True)
txt.setAcceptRichText(False)
txt.setText(text)
txt.selectAll()
vbox.addWidget(txt)
hbox = QHBoxLayout()
hbox.addStretch()
btn = QPushButton("Close")
btn.clicked.connect(self.close) # type: ignore[arg-type]
hbox.addWidget(btn)
vbox.addLayout(hbox)
示例13: respond
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def respond(self, content: Union[str, MessageEventContent],
event_type: EventType = EventType.ROOM_MESSAGE, markdown: bool = True,
allow_html: bool = False, reply: Union[bool, str] = False,
edits: Optional[Union[EventID, MessageEvent]] = None) -> Awaitable[EventID]:
if isinstance(content, str):
content = TextMessageEventContent(msgtype=MessageType.NOTICE, body=content)
if allow_html or markdown:
content.format = Format.HTML
content.body, content.formatted_body = parse_formatted(content.body,
render_markdown=markdown,
allow_html=allow_html)
if edits:
content.set_edit(edits)
elif reply:
if reply != "force" and self.disable_reply:
content.body = f"{self.sender}: {content.body}"
fmt_body = content.formatted_body or escape(content.body).replace("\n", "<br>")
content.formatted_body = (f'<a href="https://matrix.to/#/{self.sender}">'
f'{self.sender}'
f'</a>: {fmt_body}')
else:
content.set_reply(self)
return self.client.send_message_event(self.room_id, event_type, content)
示例14: depart_gallery_html
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def depart_gallery_html(self, node):
for title, uri, filename, tooltip in node['entries']:
if tooltip:
tooltip = ' tooltip="{}"'.format(html.escape(tooltip))
self.body.append("""\
<div class="sphx-glr-thumbcontainer"{tooltip}>
<div class="figure align-center">
<img alt="thumbnail" src="{filename}" />
<p class="caption">
<span class="caption-text">
<a class="reference internal" href="{uri}">
<span class="std std-ref">{title}</span>
</a>
</span>
</p>
</div>
</div>
""".format(
uri=html.escape(uri),
title=html.escape(title),
tooltip=tooltip,
filename=html.escape(filename),
))
self.body.append('<div class="sphx-glr-clear"></div>')
示例15: __init__
# 需要导入模块: import html [as 别名]
# 或者: from html import escape [as 别名]
def __init__(self, ref, excIndex):
BadgeItemBase.__init__(self, ref, 'x')
s = ref.canvas.settings
ColorMixin.__init__(self, ref.ref.exceptParts[excIndex],
s.exceptScopeBGColor,
s.exceptScopeFGColor, s.exceptScopeBorderColor)
QGraphicsRectItem.__init__(self)
self.kind = CellElement.SCOPE_EXCEPT_BADGE
self.excIndex = excIndex # Except block index
lines = ref.ref.exceptParts[excIndex].getDisplayValue().splitlines()
if len(lines) > 1:
exc = 'except: ' + lines[0] + '...'
elif len(lines) == 1:
exc = 'except: ' + lines[0]
else:
exc = 'except:'
self.setToolTip('<pre>' + escape(exc) + '</pre>')
# To make double click delivered
self.setFlag(QGraphicsItem.ItemIsSelectable, True)