本文整理汇总了Python中flask.Markup.escape方法的典型用法代码示例。如果您正苦于以下问题:Python Markup.escape方法的具体用法?Python Markup.escape怎么用?Python Markup.escape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.Markup
的用法示例。
在下文中一共展示了Markup.escape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pretty
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def pretty(value):
if isinstance(value, dict):
page = markup.page()
page.ul(_class='dict')
for k, v in value.items():
if isinstance(v, list) and v:
pretty_value = Markup.escape(', '.join(v))
elif isinstance(v, dict) and v:
subul = markup.page()
subul.ul(_class='subdict')
for subk, subv in v.items():
subul.li()
subul.span('%s: ' % subk)
subul.span(Markup.escape(subv))
subul.li.close()
subul.ul.close()
pretty_value = subul()
elif v:
pretty_value = Markup.escape(v)
else:
continue
page.li()
page.span('%s:' % k.capitalize().replace('_', ' '))
page.span(pretty_value)
page.li.close()
page.ul.close()
return page()
elif isinstance(value, list):
return Markup.escape(', '.join(value))
else:
page = markup.page()
page.span(Markup.escape(value), _class='simple')
return page()
示例2: lists_edit
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def lists_edit(name=None):
if 'username' not in session: return goto_login(fname(), fparms())
action = 'delete' if request.args.get('action', request.form.get('action')) == 'delete' else 'add'
item = request.args.get('item', request.form.get('item'))
if not name or not action or not item:
return redirect(url_for('lists'))
listname = getattr(userlists, name).printedname
if request.method == 'POST':
if name == 'whitelist':
restartstring = '<span class="halflink" onclick="document.getElementById(\'restartform\').submit();">Restart</span> the server to apply your changes.'
else:
restartstring = ''
if action == 'add':
if getattr(userlists, name).add(item):
flash('<i>%s</i> added to %s. %s' % (Markup.escape(item), listname, restartstring), 'success')
else:
flash('<i>%s</i> is already in %s.' % (Markup.escape(item), listname), 'info')
elif action == 'delete':
if getattr(userlists, name).remove(item):
flash('<i>%s</i> deleted from %s. %s' % (Markup.escape(item), listname, restartstring), 'success')
else:
flash('<i>%s</i> is not in %s.' % (Markup.escape(item), listname), 'info')
returnpage = request.form.get('returnpage', 'lists')
return redirect(url_for(returnpage, username=item))
return render_template('lists_delete.html', navigation=get_navi('lists'), name=name, action=action, item=item, listname=listname)
示例3: _format_attrs
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def _format_attrs(attrs, escape_attrs=True):
out = []
for name, value in sorted(attrs.items()):
if escape_attrs:
name = Markup.escape(name)
value = Markup.escape(value)
out.append(' {name}="{value}"'.format(name=name, value=value))
return ''.join(out)
示例4: safe_non_valid_input_error
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def safe_non_valid_input_error(user_input,field_name):
r"""
Returns a formatted error message where all non-fixed parameters
(in particular user input) is escaped.
"""
msg = Markup("Error: <span style='color:black'>")+Markup.escape(user_input)
msg += Markup("</span>")
msg += Markup(" is not a valid input for <span style='color:black'>")
msg += Markup.escape(field_name)+Markup("</span>")
return msg
示例5: add_new_language
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def add_new_language():
user = fetch_id_from_userid(current_user.id)
bcp = request.args.get('bcp', None)
bcp = str(Markup.escape(bcp))
iso = request.args.get('iso', None)
iso = str(Markup.escape(iso))
name = request.args.get('name', None)
name = str(Markup.escape(name))
if bcp and name:
dbinsert = insert_new_language(bcp, iso, name, user)
return jsonify(result=dbinsert)
else:
return jsonify(result=False)
示例6: td_contents
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def td_contents(self, item, attr_list, btn_class=None):
if btn_class:
return '<form method="post" action="{url}">'\
'<button class="{btn_class}" type="submit">{text}</button>'\
'</form>'.format(
url=self.url(item),
text=Markup.escape(self.text(item, attr_list)),
btn_class=btn_class)
else:
return '<form method="post" action="{url}">'\
'<button type="submit">{text}</button>'\
'</form>'.format(
url=self.url(item),
text=Markup.escape(self.text(item, attr_list)))
示例7: handle_starttag
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def handle_starttag(self, tag, attrs):
self.container.append("<%s>" % tag)
attrs_string = ''
if attrs:
for attr in attrs:
str = '%s="%s" ' % (attr[0], attr[1])
attrs_string = attrs_string + str
if attrs_string and attrs_string[-1] == " ":
attrs_string = attrs_string[:-1]
tag_string = Markup.escape('<%s %s>' % (tag, attrs_string))
else:
tag_string = Markup.escape('<%s>' % tag)
self.div_wrap = self.div_wrap + Markup('<span class="slack-%s">' % tag) + \
tag_string + Markup('</span>')
示例8: deleteUser
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def deleteUser(id):
with app.app_context():
db = get_db()
user = db.getUserByID(id)
if user is not None:
db.deleteUser(id)
db.commit()
flash('{0} {1} has been succesfully deleted.'
.format(Markup.escape(user['name']),
Markup.escape(user['surname'])),
'success')
else:
flash('Unable to delete user id {0}: User does not exist.'.format(id), 'error')
return redirect(url_for('index'))
示例9: profile_edit
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def profile_edit(user_id=-1):
""" изменение профиля пользователя
"""
user = current_user
if session and session['logged_in']:
# если юзер залогинен
if user_id >= 0:
if 'super_admin' in user.roles:
# если запрошен user_id и если есть роль admin
user = load_user(user_id)
else:
return redirect(url_for('users.profile'))
# возвращаем форму изменения профайла
if request.method == 'GET':
return render_template("users/profile_edit.html", user=user)
# все остальное это POST запрос, т.е. submit на форму изменения профиля
# валидируем форму
valid, error = profile_edit_validate(request.form, user)
if not valid:
return render_template("users/profile_edit.html", error=error, user=user)
name = ""
if 'name' in request.form:
name = Markup.escape(request.form['name'])
surname = ""
if 'surname' in request.form:
surname = Markup.escape(request.form['surname'])
if 'new_password' in request.form:
# если админ редактирует профиль и оставляет пароль пустым,
# то не меняем этот пароль
if 'super_admin' not in current_user.roles:
user.set_password(request.form['new_password'])
else:
# если админ редактирует запись, и вбивает пользователю
# новый пароль, то устанавливаем его
if request.form['old_password'] == '':
user.set_password(request.form['new_password'])
# изменяем пользователя
user['surname'] = surname
user['name'] = name
user.save()
return redirect(request.args.get('next') or url_for('users.profile'))
示例10: post_item
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def post_item(name=None):
if 'logged_in' in session:
uid = session['user_id']
g.db = connect_db(app.config['USER_DB'])
droits = get_droits(uid)
g.db.close()
if droits['adm'] == 1:
if (request.method == 'POST'):
g.db = connect_db(app.config['USER_DB'])
cur = g.db.execute('select id from items where nam like ?',
[request.form['nam']])
entries = [dict(name=row[0]) for row in cur.fetchall()]
if len(entries) == 0:
g.db.execute('insert into items (nam, price, recette, use_in, tooltip, tooltip_untouch, des, categorie) values (?, ?, ?, ?, ?, ?, ?, ?)',
[request.form['nam'], request.form['prix'],
request.form['recette'],
request.form['use_in'],
markdown.markdown(Markup.escape(request.form['tooltip'])),
request.form['tooltip'],
request.form['des'], request.form['categorie']])
g.db.commit()
else:
g.db.execute('update items set price = ?, recette = ?, use_in = ?, tooltip = ?, tooltip_untouch = ?, des = ?, categorie = ? where nam like ?',
[request.form['prix'],
request.form['recette'],
request.form['use_in'],
markdown.markdown(Markup.escape(request.form['tooltip'])),
request.form['tooltip'],
request.form['categorie'], request.form['des']])
g.db.commit()
g.db.close()
return redirect(url_for('item', name = request.form['nam']))
else:
if name == None:
return render_template('post_item.html')
else:
g.db = connect_db(app.config['USER_DB'])
cur = g.db.execute('select * from items where nam like ?',
[name])
entries = [dict(id_item=row[0], nam=row[1], prix=row[2],
recette=row[3], use_in=row[4],
tooltip=row[6],
des=row[7], cat=row[8]) for row in cur.fetchall()]
g.db.close()
if (len(entries) == 0):
return render_template('post_item.html')
else:
return render_template('post_item.html',
entries = entries)
return redirect(url_for('default'))
示例11: signup
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def signup():
""" регистрация пользователя
"""
error = None
# проверяем доступна ли регистрация
if 'REGISTRATION_ENABLED' in current_app.config:
if current_app.config['REGISTRATION_ENABLED'] == False:
# если регистрация отключена, и есть пользователи в БД,
# то показываем форму логина
if get_users_count():
return redirect(url_for('users.signin'))
# возвращаем форму логина
if request.method == 'GET':
return render_template("users/signup.html")
# остальное, метод POST, т.е. начинаем регистрацию
# валидируем форму
valid, error = signup_validate(request.form)
if not valid:
return render_template("users/signup.html", error=error)
surname = None
if 'surname' in request.form:
surname = Markup.escape(request.form['surname'])
name = None
if 'name' in request.form:
name = Markup.escape(request.form['name'])
# регистрируем нового пользователя
user = User(user_name=Markup.escape(request.form['username']),
name=name,
surname=surname,
password='',
email=Markup.escape(request.form['email']),
enabled=True)
user.set_password(request.form['password'])
# если это первый созданный пользователь, то он
# автоматом получает права администратора
if not get_users_count():
user.roles = ['super_admin']
user.save()
return redirect(url_for('users.signin'))
示例12: inventory
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def inventory():
db = get_db()
form=InventoryAddForm()
if form.validate_on_submit():
item_name = Markup.escape(request.form['item']) # escape the search term before broadcasting it!
price = Markup.escape(request.form['price'])
db.execute("insert into items (itm_name, usr, prc) values(?, ?, ?);",[item_name,g.user.id, price])
db.commit()
cur = db.execute("select itm_id, itm_name, prc from items where usr=?",[g.user.id])
items = cur.fetchall()
return render_template("inventory.html", user=g.user, items=items, form=form)
示例13: create_new_room
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def create_new_room(r, room_id, request):
max_participants= request.form["participants"]
try:
max_participants= int(max_participants)
except Exception as e:
print("Exception: main.create_new_room:",e)
max_participants= ''
room_info={"room_kind":request.form["room_kind"], "room_title":Markup.escape(request.form["title"]),
"max_participants":max_participants, "cur_participants":0, "open_time":str(time.time())}
room_data={"room_seq":room_id, "room_title": room_info["room_title"], "room_kind": room_info["room_kind"],
"open_time": room_info["open_time"], "max_participants": room_info["max_participants"],
"voted_members":[], "out_dated":False}
g.MongoDao.insert_room(room_data)
if g.MongoDao.add_room_to_tag("tag_me", room_id, 0, 0)["updatedExisting"]== False:
g.MongoDao.insert_tag("tag_me", room_id, 0, 0)
if request.form["room_kind"]== "versus":
room_data={"room_seq":room_id+"_supportA", "room_title": "", "room_kind": "support",
"open_time": room_info["open_time"], "max_participants": room_info["max_participants"],
"voted_members":[], "out_dated":False}
g.MongoDao.insert_room(room_data)
room_data={"room_seq":room_id+"_supportB", "room_title": "", "room_kind": "support",
"open_time": room_info["open_time"], "max_participants": room_info["max_participants"],
"voted_members":[], "out_dated":False}
g.MongoDao.insert_room(room_data)
示例14: blockcode
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def blockcode(self, text, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % Markup.escape(text)
lexer = pygments.lexers.get_lexer_by_name(lang, stripall=True)
formatter = pygments.formatters.HtmlFormatter()
rendered = pygments.highlight(text, lexer, formatter)
return rendered
示例15: comment_id
# 需要导入模块: from flask import Markup [as 别名]
# 或者: from flask.Markup import escape [as 别名]
def comment_id():
user = fetch_id_from_userid(current_user.id)
ili_id = request.args.get('ili_id', None)
comment = request.args.get('comment', None)
comment = str(Markup.escape(comment))
dbinsert = comment_ili_id(ili_id, comment, user)
return jsonify(result=dbinsert)