本文整理汇总了Python中flask.Markup.replace方法的典型用法代码示例。如果您正苦于以下问题:Python Markup.replace方法的具体用法?Python Markup.replace怎么用?Python Markup.replace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.Markup
的用法示例。
在下文中一共展示了Markup.replace方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: slugify
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import replace [as 别名]
def slugify(value, substitutions=()):
'''
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
Took from Django sources.
'''
# TODO Maybe steal again from current Django 1.5dev
value = Markup(value).striptags()
# value must be unicode per se
import unicodedata
from unidecode import unidecode
# unidecode returns str in Py2 and 3, so in Py2 we have to make
# it unicode again
value = unidecode(value)
if isinstance(value, six.binary_type):
value = value.decode('ascii')
# still unicode
value = unicodedata.normalize('NFKD', value).lower()
for src, dst in substitutions:
value = value.replace(src.lower(), dst.lower())
value = re.sub('[^\w\s-]', '', value).strip()
value = re.sub('[-\s]+', '-', value)
# we want only ASCII chars
value = value.encode('ascii', 'ignore')
# but Pelican should generally use only unicode
return value.decode('ascii')
示例2: home
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import replace [as 别名]
def home():
results = '';
if request.method == 'POST':
if request.form['action'] == 'start':
# run the start command
results = "Starting the server...<br /><br />"
results += check_output([app.script, "start"])
log_action(session['uid'], 4)
results = Markup(results.replace('\n', '<br />'))
elif request.form['action'] == 'stop':
# run the stop action
results = "Stoping the server...<br /><br />"
results += check_output([app.script, "stop"])
log_action(session['uid'], 6)
results = Markup(results.replace('\n', '<br />'))
elif request.form['action'] == 'restart':
# run the restart action
results = "Restarting the server...<br /><br />"
results += check_output([app.script, "restart"])
log_action(session['uid'], 5)
results = Markup(results.replace('\n', '<br />'))
elif request.form['action'] == 'update':
# run the update action
results = "Updating the server...<br /><br />"
results += check_output([app.script, "update"])
log_action(session['uid'], 7)
results = Markup(results.replace('\n', '<br />'))
else:
# invalid action!
results = "INVALID ACTION!"
g.db = connect_db()
cur = g.db.execute('SELECT time, (SELECT users.login FROM users WHERE users.id = loggedactions.user), actions.action FROM loggedactions LEFT JOIN actions ON loggedactions.action = actions.id ORDER BY time DESC LIMIT 10;')
actions = [dict(time=row[0], user=row[1], action=row[2]) for row in cur.fetchall()]
g.db.close()
return render_template('index.html', actions=actions, results=results, acp=session['priv'], username=session['username'])
示例3: t1
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import replace [as 别名]
def t1():
value = text
multiline = "\n" in value
if multiline:
value = value.replace("|"," ||").replace("\n"," |n")
if "&" in value or "<" in value:
value = Markup(Markup(value).unescape()).striptags()
# soporte multilinea
if multiline:
values = value.split(" |n")
# strip de la lista
start = 0
end = len(values)-1
while values and start<end and not values[start].strip(): start+=1
while values and end>start and not values[end].strip(): end-=1
if values and start<end:
value = "\n".join(value.replace(" ||", "|") for value in values[start:end+1])
else:
value = ""
return value
示例4: match_rcon
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import replace [as 别名]
def match_rcon(matchid):
match = Match.query.get_or_404(matchid)
admintools_check(g.user, match)
command = request.values.get('command')
server = GameServer.query.get_or_404(match.server_id)
if command:
try:
rcon_response = server.send_rcon_command(
command, raise_errors=True)
if rcon_response:
rcon_response = Markup(rcon_response.replace('\n', '<br>'))
else:
rcon_response = 'No output'
flash(rcon_response)
except util.RconError as e:
print(e)
flash('Failed to send command: ' + str(e))
return redirect('/match/{}'.format(matchid))
示例5: choose_filename
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import replace [as 别名]
def choose_filename(f,text=False):
'''
Elige el archivo correcto
'''
text=slugify(text) if text else text
srcs = f['file']['src']
fns = f['file']['fn']
chosen = None
max_count = -1
has_text = 0
try:
for hexuri,src in srcs.items():
if 'bl' in src and src['bl']!=0:
continue
this_has_text=0
for crc,srcfn in src['fn'].items():
#si no tiene nombre no se tiene en cuenta
m = srcfn['m'] if len(fns[crc]['n'])>0 else 0
if 'c' in fns[crc]:
fns[crc]['c']+=m
else:
fns[crc]['c']=m
if text:
slugified_fn = slugify(fns[crc]['n']).strip()
if len(slugified_fn)>0:
#TODO hace lo mismo que para poner el nombre en negrita y sacar el mejor texto aunque no tenga tildes o no venga unido por espacios
if slugified_fn.upper().find(text.upper())!=-1:
this_has_text = 2000
else:
matches = 0
for word in [re.escape(w) for w in text.split(" ")]:
matches += len(re.findall(r"/((?:\b|_)%s(?:\b|_))/i"%word, slugified_fn))
if matches>0:
this_has_text = 1000 + matches
f['file']['fn'][crc]['tht'] = this_has_text
better = fns[crc]['c']>max_count
if this_has_text > has_text or (better and this_has_text==has_text):
has_text = this_has_text
chosen = crc
max_count = fns[crc]['c']
except KeyError as e: #para los sources que tienen nombre pero no estan en el archivo
logging.exception(e)
f['view']['url'] = mid2url(hex2mid(f['file']['_id']))
if chosen:
filename = fns[chosen]['n']
ext = fns[chosen]['x']
else: #uses filename from src
srcurl = ""
for hexuri,src in srcs.items():
if src['url'].find("/")!=-1:
srcurl = src['url']
if srcurl=="":
return
srcurl = srcurl[srcurl.rfind("/")+1:]
ext = srcurl[srcurl.rfind(".")+1:]
filename = srcurl[0:srcurl.rfind(".")]
filename = Markup(filename).striptags()[:512]
if not ext in EXTENSIONS:
filename += ext
ext=""
nfilename = filename
else:
#clean filename
end = filename.upper().rfind("."+ext.upper())
if end == -1:
nfilename = filename
else:
nfilename = filename.strip()[0:end]
f['view']['fn'] = filename #TODO para los tipo archive buscar el tipo real en el nombre (mp3,avi...)
f['view']['fnx'] = ext
f['view']['efn'] = filename.replace(" ", "%20")
#poner bonito nombre del archivo
if nfilename.find(" ")==-1:
nfilename = nfilename.replace(".", " ")
f['view']['nfn'] = nfilename.replace("_", " ")
#nombre del archivo escapado para generar las url de descarga
f['view']['qfn'] = u(filename).encode("UTF-8")
#nombre del archivo con las palabras que coinciden con la busqueda resaltadas
if not text:# or not has_text:
f['view']['fnh'] = f['view']['fnhs'] = filename
else:
f['view']['fnh'], f['view']['fnhs'] = highlight(text,filename,True)
return has_text>0
示例6: results
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import replace [as 别名]
def results(page, url):
results = {}
url = url
print "URL in MODEL"
print url
extract = page.extract()
links_list = page.get_links()
outline = page.get_outline()
stats = page.get_stats()
headings = stats['Number of Headings']
headings = num2words(headings)
links = stats['Number of Links']
links = num2words(links)
# Format body for web. Replace new lines with spaces, add markup for styling
body = Markup(page.get_body())
body = body.replace('\n', (' '))
body = body.replace('{{', Markup('<span class="highlight">'))
body = body.replace('}}', Markup('</span>'))
body = body.replace('^', Markup('<br><span class="highlight"><br />'))
body = body.replace('*', Markup('</span><br>'))
# Encode outline and lists as json objects
store_outline = json.dumps(outline)
store_links = json.dumps(links_list)
store_stats = json.dumps(stats)
# Create and store report
r = Report(url=url, text_output=body, links=store_links, outline=store_outline, stats=store_stats)
db.session.add(r)
db.session.commit()
# Run checks
checks = page.checks()
page_report = {}
# If error found, add to report_message database
if checks['Header'] == 'header':
message = add_message(report=r, key='Header', value='header', error='header', code_snippet=None)
page_report['Header Element Present'] = message
if checks['Title'] == 'titleoveruse':
message = add_message(report=r, key='Title', value='titleoveruse', error='titleoveruse', code_snippet=None)
page_report['Title'] = message
if checks['Title'] == 'titlenone':
message = add_message(report=r, key='Title', value='titlenone', error='titlenone', code_snippet=None)
page_report['Title'] = message
if checks['Redundant Links']:
redundant_links = json.dumps(page.redundant_link())
message = add_message(report=r, key='Redundant Links', value=redundant_links, error='redundantlinks', code_snippet=redundant_links)
page_report['Redundant Links'] = [message, json.loads(redundant_links)]
if checks['Empty Links']['Total'] > 0:
empty_links = json.dumps(page.empty_links())
message = add_message(report=r, key='Empty Links', value=empty_links, error='emptylink', code_snippet=empty_links)
page_report['Empty Links'] = message
if checks['Alt Tags'] == 'alttags':
message = add_message(report=r, key='Alt Tags', value='alttags', error='alttags', code_snippet=None)
page_report['Missing Alternative Text'] = message
if checks['Headings'] == 'missingh1':
message = add_message(report=r, key='Headings', value='missingh1', error='missingh1', code_snippet=None)
page_report['Headings'] = message
if checks['Headings'] == 'noheadings':
message = add_message(report=r, key='Headings', value='noheadings', error='noheadings', code_snippet=None)
page_report['Headings'] = message
if checks['Headings'] == 'headingsskip':
message = add_message(report=r, key='Headings', value='headingsskip', error='headingsskip', code_snippet=None)
page_report['Headings Steps'] = message
if checks['Tables'] == 'layouttables':
message = add_message(report=r, key='Tables', value='layouttables', error='layouttables', code_snippet=None)
page_report['Layout Tables'] = message
if checks['Language'] == 'language':
message = add_message(report=r, key='Language', value='language', error='language', code_snippet=None)
page_report['Language'] = message
if checks['No Script'] == 'noscript':
message = add_message(report=r, key='No Script', value='noscript', error='noscript', code_snippet=None)
page_report['noscript Element Present'] = message
if checks['Form - Input Label'] == 'inputlabel':
message = add_message(report=r, key='Form - Input Label', value='inputlabel', error='inputlabel', code_snippet=None)
page_report['Missing Input Label'] = message
if checks['Form - Text Area Label'] == 'textarealabel':
message = add_message(report=r, key='Form - Text Area Label', value='textarealabel', error='textarealabel', code_snippet=None)
page_report['Missing Text Area Label'] = message
if checks['Form - Select Label'] == 'selectlabel':
message = add_message(report=r, key='Form - Select Label', value='selectlabel', error='selectlabel', code_snippet=None)
page_report['Missing Select Label'] = message
report_id = r.id
# Add report details to dict
#.........这里部分代码省略.........
示例7: instruct
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import replace [as 别名]
def instruct():
with open("INSTRUCTIONS.md") as fin:
content = markdown.markdown(fin.read())
content = Markup(content.replace("<code>", "<code class='square'>"))
# Markup to escape html characters
return render_template("instructions.html", content=content)