Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Flask Web Development

You're reading from   Mastering Flask Web Development Build enterprise-grade, scalable Python web applications

Arrow left icon
Product type Paperback
Published in Oct 2018
Publisher Packt
ISBN-13 9781788995405
Length 332 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Jack Stouffer Jack Stouffer
Author Profile Icon Jack Stouffer
Jack Stouffer
Daniel Gaspar Daniel Gaspar
Author Profile Icon Daniel Gaspar
Daniel Gaspar
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Getting Started 2. Creating Models with SQLAlchemy FREE CHAPTER 3. Creating Views with Templates 4. Creating Controllers with Blueprints 5. Advanced Application Structure 6. Securing Your App 7. Using NoSQL with Flask 8. Building RESTful APIs 9. Creating Asynchronous Tasks with Celery 10. Useful Flask Extensions 11. Building Your Own Extension 12. Testing Flask Apps 13. Deploying Flask Apps 14. Other Books You May Enjoy

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.

lock icon The rest of the chapter is locked
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.
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 $19.99/month. Cancel anytime
Banner background image