本文整理汇总了Python中xml.sax.saxutils.xml_escape函数的典型用法代码示例。如果您正苦于以下问题:Python xml_escape函数的具体用法?Python xml_escape怎么用?Python xml_escape使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了xml_escape函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: failureResult
def failureResult(err, targetService, pgt, request):
log_cas_event("Failed to issue proxy ticket", [
('client_ip', request.getClientIP()),
('targetService', targetService),
('PGT', pgt),])
if not err.check(InvalidTicket, InvalidService):
log.err(err)
code = "INTERNAL_ERROR"
msg = "An internal error occured."
if err.check(InvalidTicket):
code = "BAD_PGT"
msg = "PGT '%s' is invalid." % pgt
elif err.check(InvalidService):
code = "INVALID_SERVICE"
msg = "Target service is not authorized."
return dedent("""\
<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
<cas:proxyFailure code="%(code)s">
%(msg)s
</cas:proxyFailure>
</cas:serviceResponse>
""") % {
'code': xml_escape(code),
'msg': xml_escape(msg),
}
开发者ID:cwaldbieser,项目名称:txcas,代码行数:25,代码来源:server.py
示例2: export
def export(request):
start = request.GET.get('start')
response = HttpResponse(mimetype='application/xml')
query = Entry.all()
if start:
query.filter('word >=', start)
query.filter('valid =', True)
query.order('word')
entries = query.fetch(EXPORT_CHUNK_SIZE)
response.write('<exported-data>\n')
for entry in entries:
if not entry.valid:
continue
response.write('<Entry>\n')
response.write('<word>%s</word>\n' % entry.word)
response.write('<pos>%s</pos>\n' % entry.pos)
if entry.props:
response.write('<props>%s</props>\n' % xml_escape(entry.props))
if entry.stem:
response.write('<stem>%s</stem>\n' % entry.stem)
if entry.etym:
response.write('<etym>%s</etym>\n' % entry.etym)
if entry.comment:
response.write('<comment>%s</comment>\n' % xml_escape(entry.comment))
response.write('<editors>')
for ekey in entry.editors:
editor = db.get(ekey)
response.write('<name>%s</name>' % editor.username)
response.write('</editors>\n')
response.write('<editor>%s</editor>\n' % entry.editor.username)
response.write('<date>%s</date>\n' % entry.date.strftime('%Y-%m-%d %H:%M:%S'))
response.write('</Entry>\n')
response.write('</exported-data>\n')
return response
开发者ID:changwoo,项目名称:galkwi,代码行数:34,代码来源:tasks.py
示例3: GET
def GET(self, env, start_response):
"""
Handle GET Service request
"""
env['QUERY_STRING'] = 'format=json'
body_iter = self._app_call(env)
status = self._get_status_int()
if status != HTTP_OK:
if status in (HTTP_UNAUTHORIZED, HTTP_FORBIDDEN):
return get_err_response('AccessDenied')
else:
return get_err_response('InvalidURI')
containers = loads(''.join(list(body_iter)))
# we don't keep the creation time of a backet (s3cmd doesn't
# work without that) so we use something bogus.
if containers:
owner = containers[0].get('owner', '')
else:
owner = ''
body = '<?xml version="1.0" encoding="UTF-8"?>' \
'<ListAllMyBucketsResult ' \
'xmlns="http://doc.s3.amazonaws.com/2006-03-01">'\
'<Owner><ID>%s</ID><DisplayName>%s</DisplayName></Owner>'\
'<Buckets>%s</Buckets>' \
'</ListAllMyBucketsResult>' \
% (xml_escape(owner), xml_escape(owner),
"".join(['<Bucket><Name>%s</Name><CreationDate>'
'2009-02-03T16:45:09.000Z</CreationDate></Bucket>'
% xml_escape(i['name']) for i in containers]))
resp = Response(status=HTTP_OK, content_type='application/xml',
body=body)
return resp
开发者ID:Nexenta,项目名称:swift3,代码行数:34,代码来源:middleware.py
示例4: to_text_html_resources
def to_text_html_resources(self, retval, raw):
"""Add the resources details to the HTML output.
:param retval: The list of strings which is used to collect the HTML
response.
:type retval: list
:param raw: The original return value of this resources :func:`GET`
method.
:type raw: Dictionary
"""
for resource in raw:
retval.append('<div class="resource_details">')
retval.append('<h2 id="{0}">{0}</h2>'.format(
xml_escape(resource['name'])))
if resource['desc']:
retval.append('<p class="desc">{0}</p>'.format(xml_escape(resource['desc'])))
retval.append('<table class="config">')
retval.append('<tr><th>Path</th><td>{0}</td>'.format(xml_escape(
resource['path'])))
representations = [value + ' (.' + key + ')' for key, value
in resource['properties']['EXTENSION_MAP'].iteritems()]
retval.append('<tr><th>Representations</th><td>{0}</td>'.format(
xml_escape(', '.join(representations))))
retval.append('</table>')
self.to_text_html_methods(retval, resource)
retval.append('</div>')
开发者ID:marcammann,项目名称:wsgiservice,代码行数:26,代码来源:resource.py
示例5: __init__
def __init__(self, app, name, hotkey):
self.app = app
self.name = name
self.hotkey = hotkey
# configuration values
self.examination_time = self.app.conf["examination_time"]
# remove window from container
builder = self.app.create_builder()
self.window = builder.get_object("player_window")
container = builder.get_object("player_window_container")
container.remove(self.window)
# set player name
builder.get_object("player_name").set_markup(self.player_markup % xml_escape(name))
# attach
self.app.attach(self)
builder.get_object("stop_button_label").set_markup(self.button_markup % xml_escape(button_name(self.hotkey)))
# cache object refs
self.time_label = builder.get_object("time_label")
self.reset()
builder.connect_signals(self)
self.window.show()
开发者ID:Borsos,项目名称:rubik-7,代码行数:28,代码来源:rubik.py
示例6: saveXML
def saveXML(self):
try:
fp = file(self.filename, 'w')
fp.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n")
fp.write("<ci>\n")
fp.write("\t<slot>\n")
fp.write("\t\t<id>%s</id>\n" % self.ci_slot)
for item in self.selectedcaid:
if len(self.selectedcaid):
fp.write("\t\t<caid id=\"%s\" />\n" % item[0])
for item in self.servicelist:
if len(self.servicelist):
psname = xml_escape(item[0])
psattr = xml_escape(item[3])
if item[2]==1:
fp.write("\t\t<provider name=\"%s\" dvbnamespace=\"%s\" />\n" % (psname, psattr))
else:
fp.write("\t\t<service name=\"%s\" ref=\"%s\" />\n" % (psname, psattr))
fp.write("\t</slot>\n")
fp.write("</ci>\n")
fp.flush()
fsync(fp.fileno())
fp.close()
except:
print "[CI_Config_CI%d] xml not written" %self.ci_slot
os_unlink(self.filename)
开发者ID:OpenDMM,项目名称:enigma2,代码行数:26,代码来源:plugin.py
示例7: _notifyServicesSLO
def _notifyServicesSLO(self, services):
template = self._samlLogoutTemplate
def logerr(err, service):
log.msg("Error sending SLO to service '%s'." % service)
log.err(err)
errs = unwrap_failures(err)
for error in errs:
log.err(error)
return err
dlist = []
for service, st in services.iteritems():
dt = datetime.datetime.utcnow()
issue_instant = dt.strftime("%Y-%m-%dT%H:%M:%S")
identifier = str(uuid.uuid4())
data = template % {
'identifier': xml_escape(identifier),
'issue_instant': xml_escape(issue_instant),
'service_ticket': xml_escape(st)
}
httpClient = self.httpClientFactory(self.reactor)
d = httpClient.post(
service.encode('utf-8'),
headers=Headers({'Content-Type': ['application/xml']}),
data=data.encode('utf-8'),
timeout=30).addCallback(
treq.content).addErrback(
logerr, service)
dlist.append(d)
return defer.DeferredList(dlist, consumeErrors=True)
开发者ID:cwaldbieser,项目名称:txcas,代码行数:31,代码来源:couchdb_ticket_store.py
示例8: upload_results
def upload_results(self, results, path, message=None):
""" Upload query results CSV to Amazon S3
:param tuple results: query results for upload
:param str path: bucket path
:param str message: text to display before download link
:return: link text on successful upload, failure message if
s3 upload failed
"""
timer = statsd.timer('bux_sql_grader.upload_results').start()
if not message:
message = "Download full results"
# Convert result rows to CSV
csv_results = self.csv_results(results)
# Upload to S3
s3_url = self.upload_to_s3(csv_results, path)
if s3_url:
context = {"url": xml_escape(s3_url), "message": xml_escape(message),
"icon_src": xml_escape(self.download_icon)}
download_link = DOWNLOAD_LINK.substitute(context)
else:
download_link = UPLOAD_FAILED_MESSAGE
timer.stop()
return download_link
开发者ID:abduld,项目名称:bux-sql-grader,代码行数:28,代码来源:mysql.py
示例9: renderFailure
def renderFailure(err, ticket, request):
log_cas_event("Failed to validate ticket.", [
('client_ip', request.getClientIP()),
('ticket', ticket)])
err.trap(InvalidTicket, InvalidProxyCallback, InvalidService)
request.setResponseCode(403)
code = "INVALID_TICKET"
msg = "Validation failed for ticket '%s'." % ticket
if err.check(InvalidTicketSpec):
code = "INVALID_TICKET_SPEC"
elif err.check(InvalidProxyCallback):
code = "INVALID_PROXY_CALLBACK"
msg = "Invalid proxy callback."
elif err.check(InvalidService):
code = "INVALID_SERVICE"
msg = "Invalid service."
doc_fail = dedent("""\
<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
<cas:authenticationFailure code="%(code)s">
%(msg)s.
</cas:authenticationFailure>
</cas:serviceResponse>
""") % {
'code': xml_escape(code),
'msg': xml_escape(msg),}
return doc_fail
开发者ID:cwaldbieser,项目名称:txcas,代码行数:26,代码来源:server.py
示例10: create_xml
def create_xml(self):
template = u'<attendees><person>%(first)s%(last)s%(email)s</person>%(session_key)s<joinStatus>ACCEPT</joinStatus><emailInvitations>TRUE</emailInvitations></attendees>'
template_bits = {
'first': self.first_name and '<firstName>%s</firstName>'%xml_escape(self.first_name) or '',
'last': self.last_name and '<lastName>%s</lastName>'%xml_escape(self.last_name) or '',
'email': '<email>%s</email>'%xml_escape(self.email),
'session_key': '<sessionKey>%s</sessionKey>'%self.event.session_key }
return template % template_bits
开发者ID:prior,项目名称:webexpy,代码行数:8,代码来源:registrant.py
示例11: create_xml
def create_xml(cfg):
""" convert config dict to xml """
xml= "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n"
xml += "<map>\n"
for k,v in cfg.items():
xml += " <string name=\"%s\">%s</string>\n" % (xml_escape(k), xml_escape(v))
xml += "</map>\n"
return xml
开发者ID:AntoineLee,项目名称:cocdp,代码行数:9,代码来源:cocprefs.py
示例12: build_response
def build_response(self, correct, score, hints, student_results,
student_warnings=[], grader_results=None,
grader_warnings=[], row_limit=None,
download_link=""):
""" Builds a grader response dict. """
response = {"correct": correct, "score": score}
# Response message template context
context = {"download_link": download_link, "hints": ""}
# Generate student response results table
context["student_results"] = self.html_results(student_results,
row_limit)
# Generate warning messages if queries had to be modified
notices = ""
if student_warnings:
student_warnings = [xml_escape(notice) for notice in student_warnings]
student_warning = "<strong>Warning</strong><p>"
student_warning += "</p><p>".join(student_warnings) + "</p>"
notices += WARNING_TMPL.substitute(msg=student_warning)
if grader_warnings:
grader_warnings = [xml_escape(notice) for notice in grader_warnings]
grader_warning = "<strong>Warning</strong><p>"
grader_warning += "</p><p>".join(grader_warnings) + "</p>"
notices += WARNING_TMPL.substitute(msg=grader_warning)
context["notices"] = notices
if grader_results and not correct:
# Generate grader response results table
context["grader_results"] = self.html_results(grader_results,
row_limit)
# Generate hints markup if hints were provided
if hints:
# Ensure hint text is XML-safe
hints = [xml_escape(hint) for hint in hints]
hints_html = "<strong>Hints</strong>"
hints_html += "<ul><li>"
hints_html += "</li><li>".join(hints)
hints_html += "</li></ul>"
context["hints"] = hints_html
# Incorrect response template
response["msg"] = INCORRECT_QUERY.substitute(context)
else:
# Correct response template
response["msg"] = CORRECT_QUERY.substitute(context)
return response
开发者ID:abduld,项目名称:bux-sql-grader,代码行数:56,代码来源:mysql.py
示例13: __init__
def __init__(self, code, message=None):
assert isinstance(code, int) # Being a bit paranoid about the API
self.code = code
self.reason, self.message = http_responses[code]
if message is not None:
self.message = message
self.text = ERROR_DOCUMENT_TEMPLATE % dict(code=self.code,
reason=xml_escape(self.reason),
message=xml_escape(self.message))
self.headers = [("Content-Type", "text/html")]
开发者ID:dpla,项目名称:akara,代码行数:10,代码来源:services.py
示例14: innerXML
def innerXML(node):
if len(node) > 0:
text = xml_escape(node.text or '')
for child in node:
text += outterXML(child)
if child.tail:
text += xml_escape(child.tail)
return text or ''
else:
return xml_escape(node.text or '')
开发者ID:vincentchivas,项目名称:nautilus,代码行数:10,代码来源:res.py
示例15: _delete_multi
def _delete_multi(self, keys, force=False):
body = [ '<Delete>' ]
esc_prefix = xml_escape(self.prefix)
for key in keys:
body.append('<Object><Key>%s%s</Key></Object>' % (esc_prefix, xml_escape(key)))
body.append('</Delete>')
body = '\n'.join(body).encode('utf-8')
headers = { 'content-type': 'text/xml; charset=utf-8' }
resp = self._do_request('POST', '/', subres='delete', body=body, headers=headers)
try:
root = self._parse_xml_response(resp)
ns_p = self.xml_ns_prefix
error_tags = root.findall(ns_p + 'Error')
if not error_tags:
# No errors occured, everything has been deleted
del keys[:]
return
# Some errors occured, so we need to determine what has
# been deleted and what hasn't
offset = len(self.prefix)
for tag in root.findall(ns_p + 'Deleted'):
fullkey = tag.find(ns_p + 'Key').text
assert fullkey.startswith(self.prefix)
keys.remove(fullkey[offset:])
if log.isEnabledFor(logging.DEBUG):
for errtag in error_tags:
log.debug('Delete %s failed with %s',
errtag.findtext(ns_p + 'Key')[offset:],
errtag.findtext(ns_p + 'Code'))
# If *force*, just modify the passed list and return without
# raising an exception, otherwise raise exception for the first error
if force:
return
errcode = error_tags[0].findtext(ns_p + 'Code')
errmsg = error_tags[0].findtext(ns_p + 'Message')
errkey = error_tags[0].findtext(ns_p + 'Key')[offset:]
if errcode == 'NoSuchKeyError':
raise NoSuchObject(errkey)
else:
raise get_S3Error(errcode, 'Error deleting %s: %s' % (errkey, errmsg))
finally:
# Need to read rest of response
while True:
buf = resp.read(BUFSIZE)
if buf == b'':
break
开发者ID:abc3267454,项目名称:s3ql,代码行数:55,代码来源:s3.py
示例16: build_translation_memory_file
def build_translation_memory_file(creation_date, locale_code, entries):
"""
TMX files will contain large amount of entries and it's impossible to render all the data with
django templates.
Rendering of string in memory is a lot faster.
:arg datetime creation_date: when TMX file is being created.
:arg str locale_code: code of a locale
:arg list entries: A list which contains tuples with following items:
* resource_path - path of a resource,
* key - key of an entity,
* source - source string of entity,
* target - translated string,
* project_name - name of a project,
* project_slug - slugified name of a project,
"""
yield (
u'<?xml version="1.0" encoding="utf-8" ?>'
u'\n<tmx version="1.4">'
u'\n\t<header'
u' adminlang="en-US"'
u' creationtoolversion="0.1"'
u' creationtool="pontoon"'
u' datatype="plaintext"'
u' segtype="sentence"'
u' o-tmf="plain text"'
u' srclang="en-US"'
u' creationdate="%(creation_date)s">'
u'\n\t</header>'
u'\n\t<body>' % {
'creation_date': creation_date.isoformat()
}
)
for resource_path, key, source, target, project_name, project_slug in entries:
tuid = ':'.join((project_slug, slugify(resource_path), slugify(key)))
yield (
u'\n\t\t<tu tuid=%(tuid)s srclang="en-US">'
u'\n\t\t\t<tuv xml:lang="en-US">'
u'\n\t\t\t\t<seg>%(source)s</seg>'
u'\n\t\t\t</tuv>'
u'\n\t\t\t<tuv xml:lang=%(locale_code)s>'
u'\n\t\t\t\t<seg>%(target)s</seg>'
u'\n\t\t\t</tuv>'
u'\n\t\t</tu>' % {
'tuid': quoteattr(tuid),
'source': xml_escape(source),
'locale_code': quoteattr(locale_code),
'target': xml_escape(target),
'project_name': xml_escape(project_name),
}
)
yield (
u'\n\t</body>'
u'\n</tmx>'
)
开发者ID:Pike,项目名称:pontoon,代码行数:55,代码来源:utils.py
示例17: cfg2dot
def cfg2dot(fin, fout):
import json
src = json.load(fin)['cfgs']
fout.write('digraph G {\n')
fout.write(' node [shape=record];\n')
fnidx = 0
for fnname, fn in src.iteritems():
skipexit2 = True
for node in fn['nodes']:
for succ in node[1]:
if succ[1] != 2 and fn['nodes'][succ[0]][0] == 'exit' and fn['nodes'][succ[0]][2][0][1] == '2':
skipexit2 = False
break
if not skipexit2:
break
fout.write(' entry%d [label="%s"];\n' % (fnidx, xml_escape(fnname)))
fout.write(' entry%d -> node%d_%d;\n' % (fnidx, fnidx, fn['entry']))
for i, node in enumerate(fn['nodes']):
if skipexit2 and node[0] == 'exit' and node[2][0][1] == '2':
continue
if node[0] == 'call':
ops = node[2][1:]
opstr = node[2][0][1] + '('
elif node[0] == 'value':
ops = node[2]
opstr = ''
else:
ops = node[2]
opstr = node[0] + '['
args = []
for op in ops:
if op[0] == 'varptr':
args.append('&' + str(op[1]))
elif op[0] != 'node':
args.append(str(op[1]))
else:
args.append('$' + str(op[1]))
opstr = opstr + ', '.join(args)
if node[0] == 'call':
opstr = opstr + ')'
elif node[0] != 'value':
opstr = opstr + ']'
fout.write(' node%d_%d [label="<f1> %d |<f2> %s"];\n' % (fnidx, i, i, xml_escape(opstr)));
for succ in node[1]:
if succ[1] == 0:
fout.write(' node%d_%d -> node%d_%d [label="%s"];\n' % (fnidx, i, fnidx, succ[0], xml_escape(convert_sir_const(succ[2]))))
if succ[1] == 1:
fout.write(' node%d_%d -> node%d_%d [label="%s",style="dotted"];\n' % (fnidx, i, fnidx, succ[0], xml_escape(convert_sir_const(succ[2]))))
fnidx += 1
fout.write('}')
开发者ID:avakar,项目名称:cpp2sir,代码行数:53,代码来源:cfg2dot.py
示例18: markdown_first_paragraph
def markdown_first_paragraph(text):
try:
rendered = markdown(text, safe_mode='escape')
# Extract the contents of the first <p>
root = lxml.etree.fromstring('<div>' + rendered + '</div>')
first_para = root.find('p')
html_content = ''.join(
[xml_escape(first_para.text or '')] +
[lxml.etree.tostring(child) for child in first_para.iterchildren()] +
[xml_escape(first_para.tail or '')])
return XML(html_content)
except Exception:
return text
开发者ID:beaker-project,项目名称:beaker,代码行数:13,代码来源:helpers.py
示例19: upsert_xml
def upsert_xml(self):
return u"""
<accessControl><listing>%s</listing>%s</accessControl>%s
<schedule><startDate>%s</startDate><duration>%s</duration><timeZoneID>%s</timeZoneID></schedule>
<metaData><sessionName>%s</sessionName><description>%s</description></metaData> """ % (
self.visibility.upper(),
self.account.meetings_require_password and '<sessionPassword>0000</sessionPassword>' or '',
self.session_key and ('<sessionKey>%s</sessionKey>'%self.session_key) or '',
self.starts_at.strftime("%m/%d/%Y %H:%M:%S"),
(self.ends_at-self.starts_at).m,
timezone.get_id(self.starts_at.tz.zone),
xml_escape(self.title),
xml_escape(self.description))
开发者ID:prior,项目名称:webexpy,代码行数:13,代码来源:event.py
示例20: format_lexc_xml
def format_lexc_xml(wordmap):
analysis = xml_escape(wordmap["lemma"])
analysis = analysis.replace("|", '<s mcs="wb"/>').replace("_", '<s mcs="mb"/>')
analysis += '<s mcs="' + wordmap["pos"] + '"/>'
if wordmap["is_proper"]:
analysis += '<s mcs="proper"/>'
if wordmap["is_suffix"]:
analysis = "<s mcs='suffix'/>" + analysis
if wordmap["is_prefix"]:
analysis += "<s mcs='prefix'/>"
stub = xml_escape(wordmap["stub"])
stub = stub.replace("|", '<s mcs="wb"/>').replace("_", '<s mcs="mb"/>')
return ' <e><a>%s</a><i>%s</i><cont lexica="%s"/></e>' % (analysis, stub, wordmap["new_para"])
开发者ID:redox-alpha,项目名称:omorfi,代码行数:13,代码来源:experimental_xml_formatter.py
注:本文中的xml.sax.saxutils.xml_escape函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论