Book Image

Mastering Flask Web Development - Second Edition

By : Daniel Gaspar, Jack Stouffer
Book Image

Mastering Flask Web Development - Second Edition

By: Daniel Gaspar, Jack Stouffer

Overview of this book

Flask is a popular Python framework known for its lightweight and modular design. Mastering Flask Web Development will take you on a complete tour of the Flask environment and teach you how to build a production-ready application. You'll begin by learning about the installation of Flask and basic concepts such as MVC and accessing a database using an ORM. You will learn how to structure your application so that it can scale to any size with the help of Flask Blueprints. You'll then learn how to use Jinja2 templates with a high level of expertise. You will also learn how to develop with SQL or NoSQL databases, and how to develop REST APIs and JWT authentication. Next, you'll move on to build role-based access security and authentication using LDAP, OAuth, OpenID, and database. Also learn how to create asynchronous tasks that can scale to any load using Celery and RabbitMQ or Redis. You will also be introduced to a wide range of Flask extensions to leverage technologies such as cache, localization, and debugging. You will learn how to build your own Flask extensions, how to write tests, and how to get test coverage reports. Finally, you will learn how to deploy your application on Heroku and AWS using various technologies, such as Docker, CloudFormation, and Elastic Beanstalk, and will also learn how to develop Jenkins pipelines to build, test, and deploy applications.
Table of Contents (15 chapters)

The beginning of our project

Finally, we can get to our first Flask project. In order to build a complex project at the end of this book, we will need a simple Flask project to start us off.

Simple application

Flask is very powerful, but will most definitely not get in your way. You can use it to create a simple web application using a single file. Our aim is to create a project that is structured in a way that it can scale and be easy to understand. For now, we will create a config file first. In the file named config.py, add the following:

class Config(object): 
    pass 
 
class ProdConfig(Config): 
    pass 
 
class DevConfig(Config): 
    DEBUG = True 

Now, in another file named main.py, add the following:

from flask import Flask 
from config import DevConfig 
 
app = Flask(__name__) 
app.config.from_object(DevConfig) 
 
@app.route('/') 
def home(): 
    return '<h1>Hello World!</h1>' 
 
if __name__ == '__main__': 
    app.run() 

For anyone who is familiar with the base Flask API, this program is very basic. It will simply show Hello World! on the browser if we navigate to http://127.0.0.1:5000. One point that may be unfamiliar to Flask users is the use of the phrase config.from_object rather than app.config['DEBUG']. We use from_object because in future, multiple configurations will be used, and manually changing every variable when we need to switch between configurations is time consuming.

Project structure

We have created a very simple project structure, but can it serve as the base skeleton for any Python project. In Chapter 5, Advanced Application Structure, we will get our hands on a more scalable structure, but for now, let's go back to our environment, as shown in the following code:

Dockerfile # Instructions to configure and run our application on a container
requirements.txt # All the dependencies needed to run our application
/venv # We will not add this folder to our Git repo, our virtualenv
.gitignore # Instruction for Git to ignore files
main.py # Our main Flask application
config.py # Our configuration file

Remember to commit these changes in Git, as shown in the following code:

# The --all flag will tell git to stage all changes you have made
# including deletions and new files
$ git add --all
$ git commit -m" ""created the base application"
You will no longer be reminded of when to commit your changes to Git. It is up to you to develop the habit of committing whenever you reach a stopping point. It is also assumed that you will be operating inside the virtual environment, so all command-line prompts will not be prefixed with (env).

Using Flask's command-line interface

In order to make the next chapters easier for the reader, we will look at how to use the Flask CLI (using version 0.11 onward). The CLI allows programmers to create commands that act within the application context of Flask—that is, the state in Flask that allows the modification of the Flask object. The Flask CLI comes with some default commands to run the server and a Python shell in the application context.

Let's take a look at the Flask CLI and how to initialize it. First, we must tell it how to discover our application using the following code:

$ export FLASK_APP=main.py

Then, we will use the Flask CLI to run our application using the following code:

$ flask run

Now, let's enter the shell on the application context and see how to get all the defined URL routes, using the following code:

$ flask shell
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
App: main [debug]
Instance: /chapter_1/instance
>>> app.url_map
Map([<Rule '/' (OPTIONS, GET, HEAD) -> home>,
<Rule '/static/<filename>' (OPTIONS, GET, HEAD) -> static>])

As you can see, we already have two routes defined: the / where we display the "Hello World" sentence and the static default route created by Flask. Some other useful information shows where Flask thinks our templates and static folders are, as shown in the following code:

>>> app.static_folder
/chapter_1/static'
>>> app.template_folder
'templates'

Flask CLI, uses the click library from the creator of Flask itself. It was designed to be easily extensible so that the Flask extensions can extend it and implement new commands that are available when you use them. We should indeed extend it—it makes it more useful to extend it ourselves. This is the right way to create management commands for our applications. Think about commands that you can use to migrate database schemas, create users, prune data, and so on.