当前位置: 首页>>代码示例>>Python>>正文


Python flask.Markup方法代码示例

本文整理汇总了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) 
开发者ID:CQCumbers,项目名称:kle_render,代码行数:22,代码来源:app.py

示例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,
	)) 
开发者ID:mrphlip,项目名称:lrrbot,代码行数:23,代码来源:utils.py

示例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 
开发者ID:Flask-Middleware,项目名称:flask-security,代码行数:18,代码来源:forms.py

示例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 
开发者ID:JosXa,项目名称:BotListBot,代码行数:19,代码来源:botlistapi.py

示例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)) 
开发者ID:apache,项目名称:airflow,代码行数:26,代码来源:hive_metastore.py

示例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) 
开发者ID:apache,项目名称:airflow,代码行数:27,代码来源:utils.py

示例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 [])) 
开发者ID:veripress,项目名称:veripress,代码行数:27,代码来源:storages.py

示例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 "" 
开发者ID:radremedy,项目名称:radremedy,代码行数:18,代码来源:admin_helpers.py

示例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))) 
开发者ID:radremedy,项目名称:radremedy,代码行数:22,代码来源:admin_helpers.py

示例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'&lt;p&gt;Hello World!',
            b'<p>Hello World!',
            b'<p>Hello World!',
            b'<p>Hello World!',
            b'&lt;p&gt;Hello World!',
            b'<p>Hello World!'
        ]) 
开发者ID:chalasr,项目名称:Flask-P2P,代码行数:18,代码来源:templating.py

示例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) 
开发者ID:thecarebot,项目名称:carebot,代码行数:22,代码来源:render_utils.py

示例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) 
开发者ID:jelmerdejong,项目名称:flask-app-blueprint,代码行数:22,代码来源:views.py

示例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) 
开发者ID:jelmerdejong,项目名称:flask-app-blueprint,代码行数:24,代码来源:views.py

示例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')) 
开发者ID:jelmerdejong,项目名称:flask-app-blueprint,代码行数:23,代码来源:views.py

示例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) 
开发者ID:jelmerdejong,项目名称:flask-app-blueprint,代码行数:21,代码来源:views.py


注:本文中的flask.Markup方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。