Python flask.Markup() Examples

The following are 30 code examples of flask.Markup(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: templating.py    From syntheticmass with Apache License 2.0 6 votes vote down vote up
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!'
        ]) 
Example #2
Source File: utils.py    From airflow with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: render_utils.py    From carebot with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: hive_metastore.py    From airflow with Apache License 2.0 6 votes vote down vote up
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)) 
Example #5
Source File: views.py    From flask-app-blueprint with MIT License 6 votes vote down vote up
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')) 
Example #6
Source File: admin_helpers.py    From radremedy with Mozilla Public License 2.0 6 votes vote down vote up
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 "" 
Example #7
Source File: botlistapi.py    From BotListBot with MIT License 6 votes vote down vote up
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 
Example #8
Source File: views.py    From flask-app-blueprint with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: views.py    From flask-app-blueprint with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: storages.py    From veripress with MIT License 6 votes vote down vote up
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 [])) 
Example #11
Source File: forms.py    From flask-security with MIT License 6 votes vote down vote up
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 
Example #12
Source File: __init__.py    From flask-share with MIT License 6 votes vote down vote up
def load(css_url=None, js_url=None, serve_local=False):
        """Load share.js resources.

        :param css_url: if set, will be used as css url.
        :param js_url: if set, will be used as js url.
        :param serve_local: if set to True, the local resource will be used.
        """
        if serve_local or current_app.config['SHARE_SERVE_LOCAL']:
            css_url = url_for('share.static', filename='css/share.min.css')
            js_url = url_for('share.static', filename='js/social-share.min.js')

        if css_url is None:
            css_url = 'https://cdn.bootcss.com/social-share.js/1.0.16/css/share.min.css'
        if js_url is None:
            js_url = 'https://cdn.bootcss.com/social-share.js/1.0.16/js/social-share.min.js'
        return Markup('''<link rel="stylesheet" href="%s" type="text/css">\n
            <script src="%s"></script>''' % (css_url, js_url)) 
Example #13
Source File: utils.py    From lrrbot with Apache License 2.0 6 votes vote down vote up
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,
	)) 
Example #14
Source File: app.py    From kle_render with MIT License 6 votes vote down vote up
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) 
Example #15
Source File: admin_helpers.py    From radremedy with Mozilla Public License 2.0 6 votes vote down vote up
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))) 
Example #16
Source File: utils.py    From ok with Apache License 2.0 6 votes vote down vote up
def convert_markdown(text):
    # https://pythonadventures.wordpress.com/tag/markdown/
    allowed_tags = [
        'a', 'abbr', 'acronym', 'b',
        'blockquote', 'code', 'em',
        'i', 'li', 'ol', 'pre', 'strong',
        'ul', 'h1', 'h2', 'h3', 'p', 'br', 'ins', 'del',
    ]
    unsafe_html = markdown.markdown(
        text,
        extensions=["markdown.extensions.fenced_code"],
    )
    html = bleach.linkify(bleach.clean(unsafe_html, tags=allowed_tags))
    return Markup(html)

# Timezones. Be cautious with using tzinfo argument. http://pytz.sourceforge.net/
# "tzinfo argument of the standard datetime constructors 'does not work'
# with pytz for many timezones." 
Example #17
Source File: templating.py    From Flask-P2P with MIT License 6 votes vote down vote up
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!'
        ]) 
Example #18
Source File: views.py    From flask-app-blueprint with MIT License 6 votes vote down vote up
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) 
Example #19
Source File: tag.py    From myblog with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self):
        return Markup(f'<div>{self.content}</div>') 
Example #20
Source File: jinja.py    From maple-bbs with GNU General Public License v3.0 5 votes vote down vote up
def markdown(text, clean=True):
    renderer = HtmlRenderer()
    md = Markdown(renderer, extensions=('fenced-code', ))
    if clean:
        return Markup(safe_clean(md(text)))
    return Markup(md(text)) 
Example #21
Source File: views.py    From flask-app-blueprint with MIT License 5 votes vote down vote up
def edit_item(items_id):
    form = EditItemsForm(request.form)
    item_with_user = db.session.query(Items, User).join(User).filter(Items.id == items_id).first()
    if item_with_user is not None:
        if current_user.is_authenticated and item_with_user.Items.user_id == current_user.id:
            if request.method == 'POST':
                if form.validate_on_submit():
                    try:
                        item = Items.query.get(items_id)
                        item.name = form.name.data
                        item.notes = form.notes.data
                        db.session.commit()
                        message = Markup("Item edited successfully!")
                        flash(message, 'success')
                        return redirect(url_for('home'))
                    except:
                        db.session.rollback()
                        message = Markup(
                            "<strong>Error!</strong> Unable to edit item.")
                        flash(message, 'danger')
            return render_template('edit_item.html', item=item_with_user, form=form)
        else:
            message = Markup(
                "<strong>Error!</strong> Incorrect permissions to access this item.")
            flash(message, 'danger')
    else:
        message = Markup("<strong>Error!</strong> Item does not exist.")
        flash(message, 'danger')
    return redirect(url_for('home')) 
Example #22
Source File: tag.py    From myblog with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self):
        return Markup(f'<script type="text/javascript" src="{self.src}"></script>') 
Example #23
Source File: tag.py    From myblog with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self):
        return Markup(f'<link href="{self.href}" rel="stylesheet">') 
Example #24
Source File: views.py    From flask-app-blueprint with MIT License 5 votes vote down vote up
def confirm_email(token):
    try:
        confirm_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
        email = confirm_serializer.loads(token, salt='email-confirmation-salt', max_age=3600)
    except:
        message = Markup(
            "The confirmation link is invalid or has expired.")
        flash(message, 'danger')
        return redirect(url_for('users.login'))

    user = User.query.filter_by(email=email).first()

    if user.email_confirmed:
        message = Markup(
            "Account already confirmed. Please login.")
        flash(message, 'info')
    else:
        user.email_confirmed = True
        user.email_confirmed_on = datetime.now()
        db.session.add(user)
        db.session.commit()
        message = Markup(
            "Thank you for confirming your email address!")
        flash(message, 'success')

    return redirect(url_for('home')) 
Example #25
Source File: jinja.py    From maple-bbs with GNU General Public License v3.0 5 votes vote down vote up
def safe_clean(text):
    tags = ['b', 'i', 'font', 'br', 'blockquote', 'div', 'h2', 'a', 'p']
    attrs = {'*': ['style', 'id', 'class'], 'font': ['color'], 'a': ['href']}
    styles = ['color']
    return Markup(clean(text, tags=tags, attributes=attrs, styles=styles)) 
Example #26
Source File: base.py    From flasgger with MIT License 5 votes vote down vote up
def MK_SANITIZER(text):
    return Markup(markdown(text)) if text else text 
Example #27
Source File: render_utils.py    From carebot with MIT License 5 votes vote down vote up
def urlencode_filter(s):
    """
    Filter to urlencode strings.
    """
    if type(s) == 'Markup':
        s = s.unescape()

    # Evaulate COPY elements
    if type(s) is not unicode:
        s = unicode(s)

    s = s.encode('utf8')
    s = urllib.quote_plus(s)

    return Markup(s) 
Example #28
Source File: render_utils.py    From carebot with MIT License 5 votes vote down vote up
def render(self, path):
        if getattr(g, 'compile_includes', False):
            if path in g.compiled_includes:
                timestamp_path = g.compiled_includes[path]
            else:
                # Add a querystring to the rendered filename to prevent caching
                timestamp_path = '%s?%i' % (path, int(time.time()))

                out_path = 'www/%s' % path

                if path not in g.compiled_includes:
                    print 'Rendering %s' % out_path

                    with codecs.open(out_path, 'w', encoding='utf-8') as f:
                        f.write(self._compress())

                # See "fab render"
                g.compiled_includes[path] = timestamp_path

            markup = Markup(self.tag_string % self._relativize_path(timestamp_path))
        else:
            response = ','.join(self.includes)

            response = '\n'.join([
                self.tag_string % self._relativize_path(src) for src in self.includes
            ])

            markup = Markup(response)

        del self.includes[:]

        return markup 
Example #29
Source File: __init__.py    From Mastering-Flask-Web-Development-Second-Edition with MIT License 5 votes vote down vote up
def html(self):
        return Markup(render_template('youtube/video.html', video=self)) 
Example #30
Source File: __init__.py    From Mastering-Flask-Web-Development-Second-Edition with MIT License 5 votes vote down vote up
def html(self):
        return Markup(render_template('youtube/video.html', video=self))