Reader small image

You're reading from  Flask Framework Cookbook. - Second Edition

Product typeBook
Published inJul 2019
Reading LevelIntermediate
Publisher
ISBN-139781789951295
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Shalabh Aggarwal
Shalabh Aggarwal
author image
Shalabh Aggarwal

Shalabh Aggarwal has more than 13 years' experience in developing and managing enterprise systems, as well as web and mobile applications for small-to large-scale industries. He started his career working on Python, and although he now works on multiple technologies, he remains a Python developer at heart. He is passionate about open source technologies and writes highly readable and quality code. He is a seasoned engineering leader who loves building engineering teams and products from scratch across multiple domains while leveraging different technologies. He is also active in voluntary training for engineering students on non-conventional and open source topics. When not working with full-time assignments, he consults for start-ups on leveraging different technologies. When not writing code, he writes technical and non-technical literature, which is published across multiple blogs.
Read more about Shalabh Aggarwal

Right arrow

Working with Views

For any web application, it is very important to control how you interact with web requests and the proper responses to be catered for these requests. This chapter takes us through the various methods of handling requests properly and designing them in the best way.

Flask offers several ways of designing and laying out the URL routing for our applications. Also, it gives us the flexibility to keep the architecture of our views as just functions or to create classes, which can be inherited and modified as required. In earlier versions, Flask just had function-based views. Later, however, in version 0.7, inspired by Django, Flask introduced the concept of pluggable views, which allows us to have classes and then write methods in these classes. This also makes the process of building a RESTful API pretty simple. Also, we can always go a level deeper into Werkzeug...

Writing function-based views and URL routes

This is the simplest way of writing views and URL routes in Flask. We can just write a method and decorate it with the endpoint. In this recipe, we will write a few URL routes for GET and POST requests.

Getting ready

To go through this recipe, we can start with any Flask application. The app can be a new, empty, or any complex app. We just need to understand the methods outlined in this recipe.

How to do it...

The following section explains the three most widely used different kinds of requests, demonstrated by means of small...

Writing class-based views

Flask introduced the concept of pluggable views in version 0.7; this added a lot of flexibility to the existing implementation. We can write views in the form of classes; these views can be written in a generic fashion and allow for an easy and understandable inheritance. In this recipe, we will understand how to create such class-based views.

Getting ready

Refer to the last recipe, Writing function-based views and URL routes, to see the basic function-based views first.

How to do it...

Flask provides a class named View, which can be inherited...

Implementing URL routing and product-based pagination

At times, we may encounter a problem where we have to parse the various parts of a URL differently. For example, our URL can have an integer part, a string part, a string part of a specific length, and slashes in the URL. We can parse all these combinations in our URLs using URL converters. In this recipe, we will see how to do this. Also, we will learn how to implement pagination using the Flask-SQLAlchemy extension.

Getting ready

We have already seen several instances of basic URL converters in this book. In this recipe, we will look at some advanced URL converters and learn how to use them.

...

Rendering to templates

After writing the views, we will surely want to render the content on a template and get information from the underlying database.

Getting ready

To render to templates, we will use Jinja2 as the templating language. Refer to Chapter 2, Templating with Jinja2, to understand templating in depth.

How to do it...

We will again work in reference to our existing catalog application from the previous recipe. Let's modify our views to render templates and then display data from the database in these templates.

The following is the modified views.py...

Dealing with XHR requests

Asynchronous JavaScript XMLHttpRequest (XHR), commonly known as Ajax, has become an important part of web applications over the last few years. With the advent of single-page applications and JavaScript application frameworks such as Angular, Vue, and React, this technique of web development has risen exponentially. In this recipe, we will implement an Ajax request to facilitate asynchronous communication between the backend and frontend.

Getting ready

Flask provides an easy way to handle the XHR requests in the view handlers. We can even have common methods for normal web requests and XHRs. We can just check for a flag on our request object to determine the type of call and act accordingly.

We will...

Using decorators to handle requests beautifully

Some of us may believe that checking every time whether a request is XHR kills code readability. To solve this, we have an easy solution. In this recipe, we will write a simple decorator that can handle this redundant code for us.

Getting ready

In this recipe, we will be writing a decorator. For some Python beginners, this might seem like alien territory. In this case, read http://legacy.python.org/dev/peps/pep-0318/ for a better understanding of decorators.

How to do it...

The following is the decorator method that we have...

Creating custom 404 and 500 handlers

Every application throws errors to users at some point in time. These errors can be due to the user typing a non-existent URL (404), application overload (500), or something forbidden for a certain user to access (403). A good application handles these errors in a user-interactive way instead of showing an ugly white page, which makes no sense to most users. Flask provides an easy-to-use decorator to handle these errors. In this recipe, we will understand how we can leverage this decorator.

Getting ready

The Flask app object has a method called errorhandler(), which enables us to handle our application's errors in a much more beautiful and efficient manner.

...

Flashing messages for better user feedback

An important aspect of all good web applications is to give users feedback regarding various activities. For example, when a user creates a product and is redirected to the newly created product, then it is good practice to tell the user that the product has been created. In this recipe, we will see how flashing messages can be used as a good feedback mechanism for users.

Getting ready

We will start by adding the flash messages' functionality to our existing catalog application. We also have to make sure that we add a secret key to the application, because the session depends on the secret key, and, in the absence of the secret key, the application will error out while flashing...

Implementing SQL-based searching

In any web application, it is important to be able to search the database for records based on certain criteria. In this recipe, we will go through how to implement basic SQL-based searching in SQLAlchemy. The same principle can be used to search any other database system.

Getting ready

We have been implementing some level of search in our catalog application from the beginning. Whenever we show the product page, we search for a specific product using its ID. We will now take it to a slightly more advanced level and search on the basis of name and category.

How to do it...

...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Flask Framework Cookbook. - Second Edition
Published in: Jul 2019Publisher: ISBN-13: 9781789951295
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Shalabh Aggarwal

Shalabh Aggarwal has more than 13 years' experience in developing and managing enterprise systems, as well as web and mobile applications for small-to large-scale industries. He started his career working on Python, and although he now works on multiple technologies, he remains a Python developer at heart. He is passionate about open source technologies and writes highly readable and quality code. He is a seasoned engineering leader who loves building engineering teams and products from scratch across multiple domains while leveraging different technologies. He is also active in voluntary training for engineering students on non-conventional and open source topics. When not working with full-time assignments, he consults for start-ups on leveraging different technologies. When not writing code, he writes technical and non-technical literature, which is published across multiple blogs.
Read more about Shalabh Aggarwal