Categories
Flask

Python Web Development with Flask — Errors, Sessions, and JSON

Spread the love

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Redirects and Errors

We can redirect to another endpoint in our Flask app.

To do that, we write:

from flask import Flask, abort, redirect, url_for
app = Flask(__name__)

@app.route('/')
def index():
    return redirect(url_for('login'))

@app.route('/login')
def login():
    abort(401)

When we go to / , then we’re redirected to the /login route.

Then we get the 401 response because we called abort with the response.

We can create a 404 page by writing:

app.py

from flask import Flask, render_template
app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

templates/page_not_found.html

<p>not found</p>

Now when we go to any URL, we render the page_not_found.html template with a 404 response status code.

Response Headers

We can return headers with our response by using the make_response function to create the response.

For example, we can write:

from flask import Flask, make_response, render_template
app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(error):
    resp = make_response(render_template('page_not_found.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp

We have our 404 route.

In it, we create the response with the make_response function.

Then we pass in the template into function as the first argument.

The 2nd argument is the status code.

resp.headers is a dictionary with the headers.

Finally, we return the response object.

APIs with JSON

We can return JSON s our response.

To do that, all we have to do is return the dictionary for our JSON.

For example, we can write:

from flask import Flask
app = Flask(__name__)

@app.route("/me")
def me_api():
    return {
        "first_name": 'james',
        "last_name": 'smith'
    }

to return a dictionary in our route function.

It’ll be rendered as JSON automatically.

We can also use the jsonify function if we have anything other than a dictionary that we want to render into JSON:

from flask import Flask, jsonify
app = Flask(__name__)

@app.route("/me")
def me_api():
    users = [
        {
            'first_name': 'jane',
            'last_name': 'smith',
        },
        {
            'first_name': 'mary',
            'last_name': 'wong',
        },
    ]
    return jsonify(users)

Sessions

Flask can handle sessions automatically.

We can use the session object from the Flask module to store sessions.

For example, we can write:

from flask import Flask, session, request, redirect, url_for
from markupsafe import escape

app = Flask(__name__)
app.secret_key = b'secret'

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

We set the secret_key property to set the secret key.

In the index route function, we get the username value from the session object.

It’s a dictionary so we get the value by the key.

The login route function takes the username value from the form data if we’re making a POST request.

Then we redirect to index once that’s done.

If it’s a GET request, then we render the login form.

In the logout route function, we remove the value with the keyusername by setting it to None .

And then we redirect back to index .

Conclusion

We can do redirects, show error pages, store sessions, and return JSON easily with Flask.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *