Flask

You might also like

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 6

Flask

Flask Message Flashing - get_flashed_messages()

Flask Tip

In Flask, the get_flashed_messages() method is used to retrieve all the flash messages


(from the session).

<!-- flash messages -->


{% for message in get_flashed_messages() %}
    <p>{{ message }}</p>
{% endfor %}

flask
Posted on Twitter on Aug. 29, 2022.

Flask - Message Flashing

Flask Tip - Message Flashing

Flash messages are used to provide useful information to the user based on their actions
with the app. The flash() method is used to create a flash message to be displayed in the
next request.

from flask import request, redirect, url_for, render_template, flash

@stocks_blueprint.route('/add_stock', methods=['GET', 'POST'])


def add_stock():
        if request.method == 'POST':
                # ... save the data ...

                flash(f"Added new stock ({stock_data.stock_symbol})!")    # <-- !!


                return redirect(url_for('stocks.list_stocks'))

        return render_template('stocks/add_stock.html')

flask
Posted on Twitter on Aug. 28, 2022.

Flask Redirect

Flask Tip:

In Flask, the redirect() function is used to redirect a user to a different URL.

redirect() can greatly improve the navigation through a site by automatically redirecting


users to their expected pages.

@app.route('/add_stock', methods=['GET', 'POST'])


def add_stock():
        if request.method == 'POST':
                # ... save the data ...

                return redirect(url_for('list_stocks'))    # <-- !!

        return render_template('add_stock.html')

flask
Posted on Twitter on Aug. 26, 2022.

Creating Dynamic URLs in Flask with url_for()


Flask Tip:

In Flask, the url_for() function can be passed an argument to specify the variable part of a


URL.

# Flask View Function with Variable Routing (Python)


@stocks_blueprint.route('/stocks/<id>')
def stock_details(id):
        stock = Stock.query.filter_by(id=id).first_or_404()
        return render_template('stocks/stock_details.html', stock=stock)

# Jinja Template (HTML)


<ul>
    {% for stock in stocks %}
        <li>
            <a href="{{ url_for('stocks.stock_details',
id=stock.id) }}">{{ stock.stock_symbol }}</a>
        </li>
    {% endfor %}
</ul>

flask
Posted on Twitter on Aug. 25, 2022.

Flask URL Building with url_for()

Flask Tip:

In Flask, the url_for() function builds the URL for a specific function.

url_for() is really useful in templates to easily include URLs.

<header class="site-header">
    <a href="{{ url_for('stocks.index') }}">Flask App</a>
    <nav>
        <ul>
            <li><a href="{{ url_for('users.register') }}">Register</a></li>
            <li><a href="{{ url_for('users.login') }}">Login</a></li>
        </ul>
    </nav>
</header>

flask
Posted on Twitter on Aug. 24, 2022.

Server-side Sessions in Flask with Redis

Flask Tip:

Flask-Session works great with a Redis database!

After configuring the interface to Redis, the session object can be used (but data is stored
on the server!).

import redis
from flask import Flask, session, render_template_string
from flask_session import Session

# Create the Flask application


app = Flask(__name__)

# Configure Redis for storing the session data on the server-side


app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_REDIS'] = redis.from_url('redis://localhost:6379')

# Create and initialize the Flask-Session object AFTER `app` has been configured
server_session = Session(app)

@app.route('/get_email')
def get_email():
        return render_template_string("""<h1>Welcome {{ session['email'] }}!</h1>""")
For more, review Server-side Sessions in Flask with Redis.

flask
Posted on Twitter on Aug. 23, 2022.

How to persist sessions after closing the browser in


Flask?

By default, the session object in Flask remains in place until the browser is closed.

However, if you want to change the life of the session object, define
the PERMANENT_SESSION_LIFETIME configuration variable after creating the Flask
app:

import datetime
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=1)
When setting the data in the session, specify that the sessions should be permanent (time
will be based on PERMANENT_SESSION_LIFETIME):

# Save the form data to the session object


session['email'] = request.form['email_address']
session.permanent = True
For more, check out Sessions in Flask.

flask
Posted on Twitter on Aug. 20, 2022.

How do you "clear" only specific Flask session


variables?
In Flask, data stored in the session object can be deleted by popping a specific element
from the object.

from flask import session

@app.route('/delete_email')
def delete_email():
        # Clear the email stored in the session object
        session.pop('email', default=None)
        return '<h1>Session deleted!</h1>'
For more, review Sessions in Flask.

flask
Posted on Twitter on June 29, 2022.

Accessing Flask Session Variables in Jinja


Templates

In Flask, the session object can be read (in the same manner as a dictionary) to retrieve
data unique to the session. It's conveniently available in Jinja templates as well.

from flask import render_template_string

@app.route('/get_email')
def get_email():
        return render_template_string("""
                {% if session['email'] %}
                        <h1>Welcome {{ session['email'] }}!</h1>
                {% else %}
                        <h1>Welcome! Please enter your email <a
href="{{ url_for('set_email') }}">here.</a></h1>
                {% endif %}
        """)

You might also like