本文整理汇总了Python中flask.Markup方法的典型用法代码示例。如果您正苦于以下问题:Python flask.Markup方法的具体用法?Python flask.Markup怎么用?Python flask.Markup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask
的用法示例。
在下文中一共展示了flask.Markup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: index
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def index():
form = InputForm()
if form.validate_on_submit():
if len(form.url.data) > 0:
try:
files = github_api.get_gist(form.url.data.split('gists/', 1)[1]).files
layout = next(v for k, v in files.items() if k.endswith('.kbd.json'))
img = Keyboard(json.loads(layout.content)).render()
return serve_pil_image(img)
except (IndexError, github.GithubException):
flash('Not a valid Keyboard Layout Editor gist')
elif form.json.data:
try:
content = json.loads(form.json.data.read().decode('utf-8'))
img = Keyboard(content).render()
return serve_pil_image(img)
except ValueError:
flash(Markup('Invalid JSON input - see (?) for help'))
flash_errors(form)
return render_template('index.html', form=form)
示例2: timestamp
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def timestamp(ts, cls='timestamp', tag='span'):
"""
Outputs a given time (either unix timestamp or datetime instance) as a human-readable time
and includes tags so that common.js will convert the time on page-load to the user's
timezone and preferred date/time format.
"""
if isinstance(ts, (int, float)):
ts = datetime.datetime.fromtimestamp(ts, tz=pytz.utc)
elif ts.tzinfo is None:
ts = ts.replace(tzinfo=datetime.timezone.utc)
ts = ts.astimezone(config.config['timezone'])
if cls == 'timestamp-duration':
text = nice_duration(datetime.datetime.now(config.config['timezone']) - ts, 2)
else:
text = ts.strftime("%A, %d %B, %Y %H:%M:%S %Z")
return flask.Markup("<{tag} class=\"{cls}\" data-timestamp=\"{timestamp}\">{text}</{tag}>".format(
text=text,
timestamp=ts.timestamp(),
tag=tag,
cls=cls,
))
示例3: __init__
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.next.data:
self.next.data = request.args.get("next", "")
self.remember.default = config_value("DEFAULT_REMEMBER_ME")
if (
current_app.extensions["security"].recoverable
and not self.password.description
):
html = Markup(
'<a href="{url}">{message}</a>'.format(
url=url_for_security("forgot_password"),
message=get_message("FORGOT_PASSWORD")[0],
)
)
self.password.description = html
示例4: md2html
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def md2html(text):
text = str(text)
import textwrap
res = Markup(markdown.markdown(
textwrap.dedent(text),
[
'markdown.extensions.codehilite',
'markdown.extensions.nl2br',
'markdown.extensions.extra',
'markdown.extensions.admonition'
], extension_configs={
'markdown.extensions.codehilite': {
'noclasses': True,
'pygments_style': 'colorful'
}
}))
return res
示例5: index
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def index(self):
"""
Create default view
"""
sql = """
SELECT
a.name as db, db_location_uri as location,
count(1) as object_count, a.desc as description
FROM DBS a
JOIN TBLS b ON a.DB_ID = b.DB_ID
GROUP BY a.name, db_location_uri, a.desc
"""
hook = MySqlHook(METASTORE_MYSQL_CONN_ID)
df = hook.get_pandas_df(sql)
df.db = (
'<a href="/metastorebrowserview/db/?db=' +
df.db + '">' + df.db + '</a>')
table = df.to_html(
classes="table table-striped table-bordered table-hover",
index=False,
escape=False,
na_rep='',)
return self.render_template(
"metastore_browser/dbs.html", table=Markup(table))
示例6: task_instance_link
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def task_instance_link(attr):
"""Generates a URL to the Graph View for a TaskInstance."""
dag_id = attr.get('dag_id')
task_id = attr.get('task_id')
execution_date = attr.get('execution_date')
url = url_for(
'Airflow.task',
dag_id=dag_id,
task_id=task_id,
execution_date=execution_date.isoformat())
url_root = url_for(
'Airflow.graph',
dag_id=dag_id,
root=task_id,
execution_date=execution_date.isoformat())
return Markup(
"""
<span style="white-space: nowrap;">
<a href="{url}">{task_id}</a>
<a href="{url_root}" title="Filter on this task and upstream">
<span class="glyphicon glyphicon-filter" style="margin-left:0;"
aria-hidden="true"></span>
</a>
</span>
""").format(url=url, task_id=task_id, url_root=url_root)
示例7: search_for
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def search_for(self, query, include_draft=False):
"""
Search for a query text.
:param query: keyword to query
:param include_draft: return draft posts/pages or not
:return: an iterable object of posts and pages (if allowed).
"""
query = query.lower()
if not query:
return []
def contains_query_keyword(post_or_page):
contains = query in post_or_page.title.lower() \
or query in Markup(
get_parser(post_or_page.format).parse_whole(
post_or_page.raw_content)
).striptags().lower()
return contains
return filter(contains_query_keyword,
chain(self.get_posts(include_draft=include_draft),
self.get_pages(include_draft=include_draft)
if current_app.config[
'ALLOW_SEARCH_PAGES'] else []))
示例8: nl2br_formatter
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def nl2br_formatter(value, make_urls=True):
"""
Formats the provided value to convert newlines to line breaks.
Args:
value: The string value to format.
make_urls: If true, will attempt to auto-link URLs
detected in the string.
Returns:
The formatted, escaped HTML for the string.
"""
if value and len(value) > 0 and not value.isspace():
return Markup(get_nl2br(value, make_urls=make_urls))
else:
return ""
示例9: get_email_link
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def get_email_link(user, subject=None):
"""
Gets a properly-escaped link to email the user.
Args:
user: The user to email.
subject: The subject to use. Optional.
Returns:
A properly-escaped link to email the user.
"""
if subject and len(subject) > 0 and not subject.isspace():
subject = unicode('?subject=' + quote(subject))
else:
subject = u''
return Markup(u'<a href="mailto:%s%s">%s</a>' % (
Markup(quote(user.email)),
subject,
escape(user.email)))
示例10: test_escaping
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def test_escaping(self):
text = '<p>Hello World!'
app = flask.Flask(__name__)
@app.route('/')
def index():
return flask.render_template('escaping_template.html', text=text,
html=flask.Markup(text))
lines = app.test_client().get('/').data.splitlines()
self.assert_equal(lines, [
b'<p>Hello World!',
b'<p>Hello World!',
b'<p>Hello World!',
b'<p>Hello World!',
b'<p>Hello World!',
b'<p>Hello World!'
])
示例11: smarty_filter
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def smarty_filter(s):
"""
Filter to smartypants strings.
"""
if type(s) == 'Markup':
s = s.unescape()
# Evaulate COPY elements
if type(s) is not unicode:
s = unicode(s)
s = s.encode('utf-8')
s = smartypants(s)
try:
return Markup(s)
except:
print 'This string failed to encode: %s' % s
return Markup(s)
示例12: register
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def register():
form = RegisterForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
try:
new_user = User(form.email.data, form.password.data)
new_user.authenticated = True
db.session.add(new_user)
db.session.commit()
send_confirmation_email(new_user.email)
message = Markup(
"<strong>Success!</strong> Thanks for registering. Please check your email to confirm your email address.")
flash(message, 'success')
return redirect(url_for('home'))
except IntegrityError:
db.session.rollback()
message = Markup(
"<strong>Error!</strong> Unable to process registration.")
flash(message, 'danger')
return render_template('register.html', form=form)
示例13: reset
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def reset():
form = EmailForm()
if form.validate_on_submit():
try:
user = User.query.filter_by(email=form.email.data).first_or_404()
except:
message = Markup(
"Invalid email address!")
flash(message, 'danger')
return render_template('password_reset_email.html', form=form)
if user.email_confirmed:
send_password_reset_email(user.email)
message = Markup(
"Please check your email for a password reset link.")
flash(message, 'success')
else:
message = Markup(
"Your email address must be confirmed before attempting a password reset.")
flash(message, 'danger')
return redirect(url_for('users.login'))
return render_template('password_reset_email.html', form=form)
示例14: resend_email_confirmation
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def resend_email_confirmation():
try:
send_confirmation_email(current_user.email)
message = Markup(
"Email sent to confirm your email address. Please check your inbox!")
flash(message, 'success')
user = current_user
user.authenticated = False
db.session.add(user)
db.session.commit()
logout_user()
except IntegrityError:
message = Markup(
"Error! Unable to send email to confirm your email address.")
flash(message, 'danger')
user = current_user
user.authenticated = False
db.session.add(user)
db.session.commit()
logout_user()
return redirect(url_for('users.login'))
示例15: add_item
# 需要导入模块: import flask [as 别名]
# 或者: from flask import Markup [as 别名]
def add_item():
form = ItemsForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
try:
new_item = Items(form.name.data, form.notes.data,
current_user.id)
db.session.add(new_item)
db.session.commit()
message = Markup(
"<strong>Well done!</strong> Item added successfully!")
flash(message, 'success')
return redirect(url_for('home'))
except:
db.session.rollback()
message = Markup(
"<strong>Oh snap!</strong>! Unable to add item.")
flash(message, 'danger')
return render_template('add_item.html', form=form)