36,59 €
Learn to build modern, secure, highly available web MVC applications and API's using Python`s Flask framework.
Key Features
Book Description
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.
What you will learn
Who this book is for
The ideal target audience for this book would be Python developers who want to use Flask and its advanced features to create Enterprise grade and lightweight applications. The book is for those who have some exposure of Flask and want to take it from introductory to master level.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 379
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: AmarabhaBanerjeeAcquisition Editor: Devanshi DoshiContent Development Editor: Onkar WaniTechnical Editor: Diksha WakodeCopy Editor: Safis EditingProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Rekha NairGraphics: Alishon MendonsaProduction Coordinator: Aparna Bhagat
First published: September 2015Second Edition: October 2018
Production reference: 1301018
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78899-540-5
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Daniel Gaspar is a programmer and DevOps engineer with more than 20 years' experience. He has worked in a wide range of sectors, including government and finance. He is currently working at Miniclip (the global leader in digital games). He uses a wide range of tools in his daily work, but Flask caught his attention because of its excellently designed API and simplicity. Daniel is an OSS and Python enthusiast, and has developed a widely used extension/framework named Flask-AppBuilder, used by Airbnb on Superset and AirFlow.
Jack Stouffer is a programmer who has several years of experience in designing web applications. He switched to Flask two years ago for all his projects. He currently works for Apollo America in Auburn Hills, Michigan and writes internal business tools and software using Python, Flask, and JavaScript. Jack is a believer and supporter of open source technology. When he released his Flask examples with the recommended best practices on GitHub, it became one of the most popular Flask repositories on the site. Jack has also worked as a reviewer for Flask Framework Cookbook, Packt.
Damyan Bogoev is based in Bulgaria, where he currently works at Gtmhub as a software engineer. Prior to Gtmhub, Damyan worked at Telerik.
His background is in developing backend server applications and tools for infrastructure automation, management, and monitoring.
Damyan is also technical reviewer for the Web API Development with Flask video course.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Mastering Flask Web Development Second Edition
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started
Version control with Git
Installing Git
Git on Windows
Git basics
Git branches and flow
Python package management with pip
Installing the Python package manager on Windows
Installing pip Python package manager on macOS X and Linux
Pip basics
Dependency sandboxing with virtualenv
Virtualenv basics
Setting up Docker
The beginning of our project
Simple application
Project structure
Using Flask's command-line interface
Summary
Creating Models with SQLAlchemy
Setting up SQLAlchemy
Python packages
Flask SQLAlchemy
Our first model
Creating the user table
CRUD
Creating models
Reading models
Filtering queries
Updating models
Deleting models
Relationships between models
One-to-many relationship
Many-to-many relationship
Constraints and indexing
The convenience of SQLAlchemy sessions
Database migrations with Alembic
Summary
Creating Views with Templates
Jinja's syntax
Filters
The default filter
The escape filter
The float filter
The int filter
The join filter
The length filter
The round filter
The safe filter
The title filter
The tojson filter
The truncate filter
Custom filters
Comments
Using if statements
Loops
Macros
Flask-specific variables and functions
The config object
The request object
The session object
The url_for() function
The get_flashed_messages() function
Creating our views
The view function
Writing the templates and inheritance
The base template
The child templates
Writing the other templates
Flask WTForms
WTForms basics
Custom validations
Posting comments
Summary
Creating Controllers with Blueprints
Sessions and globals
Request setup and teardown
Error pages
Class-based views
Method class views
Blueprints
Summary
Advanced Application Structure
Modular application
Refactoring the code
Application factories
Summary
Securing Your App
Authentication methods
Basic authentication
Remote-user authentication
LDAP authentication
Database user model authentication
OpenID and OAuth
Flask-Login overview
Setting up
Updating the models
Creating the forms
Protecting your form from spam
Creating views
OpenID
OAuth
Role-based access control (RBAC)
Summary
Using NoSQL with Flask
Types of NoSQL database
Key-value stores
Document stores
Column family stores
Graph databases
RDBMS versus NoSQL
The strengths of RDBMS databases
Data integrity
Speed and scale
Tools
The strengths of NoSQL databases
CAP theorem
What database to use and when
MongoDB in Flask
Installing MongoDB
Setting up MongoEngine
Defining documents
Field types
Types of documents
The meta attribute
CRUD
Create
Write safety
Read
Filtering
Update
Delete
Relationships in NoSQL
One-to-many relationships
Many-to-many relationships
Leveraging the power of NoSQL
Summary
Building RESTful APIs
What is REST?
HTTP
REST definition and best practices
Setting up a RESTful Flask API
JWT authentication
Get requests
Output formatting
Request arguments
Post requests
Put requests
Delete requests
Summary
Creating Asynchronous Tasks with Celery
What is Celery?
Setting up Celery and RabbitMQ
Creating tasks in Celery
Running Celery tasks
Celery workflows
Partials
Callbacks
Group
Chain
Chord
Running tasks periodically
Monitoring Celery
Web-based monitoring with Flower
Creating a reminder app
Creating a weekly digest
Summary
Useful Flask Extensions
Flask CLI
Flask Debug Toolbar
Flask Caching
Caching views and functions
Caching functions with parameters
Caching routes with query strings
Using Redis as a cache backend
Using memcached as a cache backend
Flask Assets
Flask Admin
Creating basic admin pages
Creating database admin pages
Enhancing administration for the post page
Creating file system admin pages
Securing Flask Admin
Flask-Babel
Flask Mail
Summary
Building Your Own Extension
Creating a YouTube Flask extension
Creating a Python package
Creating blog posts with videos
Modifying the response with Flask extensions
Summary
Testing Flask Apps
What are unit tests?
How does testing work?
Unit testing the application
Testing the route functions
Testing security
Testing the REST API 
User interface testing
Test coverage
Test-driven development
Summary
Deploying Flask Apps
Web servers and gateway interfaces
Gevent
Tornado
Nginx and uWSGI
Apache and uWSGI
Deploying on Heroku
Using Heroku Postgres
Using Celery on Heroku
Deploying on Amazon Web Services
Using Flask on Amazon Elastic Beanstalk
Using Amazon RDS
Using Celery with Amazon SQS
Using Docker
Creating Docker images
Docker Compose
Deploying Docker containers on AWS
CloudFormation Basics
Create and update a CloudFormation stack
Building and deploying highly available applications readily
Building and deploying reliably
Creating highly available applications that scale
Monitoring and collecting logs
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Flask is a microframework with a very well designed API, designed to provide the minimum amount of functionality that is needed to create web applications. It does what it's designed to do really well. Unlike other web frameworks, Flask does not have an entire ecosystem bundled with it, no out-of-the-box features to handle databases, cache, security or form handling.
The goal of this concept is to allow programmers to design their applications or tools any way they want, no structure or design is imposed. However, because Flask community is rather large, you can find a wide range of extensions that will help you leverage Flask with a huge set of technologies. One of the main focuses of this book is to introduce these extensions and find out how they can help to avoid reinventing the wheel. The best part about these extensions is that if you don't need their extra functionalities, you don't need to include them and your app will remain small.
This book will help you structure your application to easily scale up to any size. Using packages and a simple and predictable namespace is paramount to keep maintainability and boost team productivity. This is why the other main focus of this book is how to create a Model View Controller (MVC) architecture with Flask apps.
Modern applications must go beyond well-structured code. Security, dependency isolation, environment configuration, development/production parity and ability to scale on load are factors that must not be neglected. Throughout this book, you will learn how to address these issues, identify possible risks and think ahead of time.
A large amount of research and a lot of first-hand experience of what can go wrong when developing and deploying web applications has been poured into this book. I sincerely hope you will enjoy reading it.
The ideal target audience for this book is Python developers who want to use Flask and its advanced features to create enterprise grade and lightweight applications. The book is for those who have had some exposure of Flask and want of take their skills from introductory to master level.
Chapter 1, Getting Started, helps readers set up a Flask environment for development using the best practices for Python projects. You are given a very basic skeleton Flask app that is built throughout the book.
Chapter 2, Creating Models with SQLAlchemy, shows how to use the Python database library SQLAlchemy in conjunction with Flask to create an object-oriented API for your database.
Chapter 3, Creating Views with Templates, shows how to use Flask's templating system, Jinja, to dynamically create HTML by leveraging your SQLAlchemy models.
Chapter 4, Creating Controllers with Blueprints, covers how to use Flask's blueprints feature in order to organize your view code while also avoiding repeating yourself.
Chapter 5, Advanced Application Structure, uses the knowledge gained in the last four chapters, explains how to reorganize the code files in order to create a more maintainable and testable application structure.
Chapter 6, Securing Your App, explains how to use various Flask extensions in order to add a login system with permissions-based access to each view.
Chapter 7, Using NoSQL with Flask, shows what a NoSQL database is and how to integrate one into your application when it allows more powerful features.
Chapter 8, Building RESTful APIs, shows how to provide the data stored in the application's database to third parties in a secure and easy-to-use manner.
Chapter 9, Creating Asynchronous Tasks with Celery, explains how to move expensive or time-consuming programs to the background so the application does not slow down.
Chapter 10, Useful Flask Extensions, explains how to leverage popular Flask extensions in order to make your app faster, add more features, and make debugging easier.
Chapter 11, Building Your Own Extension, teaches you how Flask extensions work and how to create your own.
Chapter 12, Testing Flask Apps, explains how to add unit tests and user interface tests to your app for quality assurance and reducing the amount of buggy code.
Chapter 13, Deploying Flask Apps, explains how to take your completed app from development to being hosted on a live server.
To get started with this book, all you will need is a text editor of your choice, a web browser, and Python installed on your machine. Windows, Mac OS X, and Linux users should all be able to easily follow along with the content of this book.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Flask-Web-Development-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Over the course of this book, you will be introduced to multiple concepts that will enable you to build a complete modern web application. You will progress from a "Hello world" web page to a complete web application that uses databases, caches, asynchronous task processing, authentication, role-based access, a REST API, and internationalization. You will learn a comprehensive way of structuring your application so that it can grow effortlessly. To choose between SQL and NoSQL technologies, you will learn how to use the most common Flask extensions to help you leverage multiple technologies, from sending emails to authentication using social media accounts. Toward the end, you will learn how to write tests, build a modern continuous integration/delivery pipeline with Docker and Jenkins, deploy your application to multiple cloud services, and know how to deal with high availability and scaling. We will tackle all of these topics with a simple and practical approach.
Flaskis the Python web framework that we are going to use. It has a very well-designed API, is very easy to learn, and makes no assumptions whatsoever as to what technology stack you are going to use, so it won't get in your way. Flask has a micro footprint, but leverages an extension system that contains hundreds of packages from a very active and vibrant community.
In this first chapter, you will learn how to set up your development environment and build your first Flask application. We will be covering the following topics:
Setting up and learning how to use Git, a powerful version control system
Learning pip, the Python management system, and how to create virtual environments with different setups
Setting up and learning the basic facts about Docker
Building a first simple Flask application
Using Python or any other language requires you to use a version control system. A version control system is a tool that records changes in files over time. This allows a programmer to revert to an earlier version of the file and identify bugs more easily. You can test new ideas without fear of breaking your current code, and your team can work using a predefined workflow without stepping on each others' toes. Git was developed by Linus Torvalds, the father of Linux. It's decentralized, light, and has great features that get the job done the right way.
Installing Git is very simple. Simply go to http://www.git-scm.com/downloads and click on the operating system (OS) that is being run. A program will begin to download will walk you through the basic installation process.
Git was originally solely developed for Unix OSes (for example, Linux and macOS X). Consequently, using Git on Windows is not seamless. During the installation, the installer will ask whether you want to install Git alongside the normal Windows Command Prompt. Do not pick this option. Choose the default option that will install a new type of command processor on your system named Bash (Bourne-again shell), which is the same command processor that the Unix systems use. Bash is much more powerful than the default Windows command line, and this is what we will be using for all the examples in this book.
Git is a very complex tool; only the basics that are needed for this book will be covered in this section.
Git does not track your changes automatically. In order for Git to run properly, we have to give it the following information:
Which folders to track
When to save the state of the code
What to track and what not to track
Before we can do anything, we have to tell Git to initialize a new git repository in our directory. Run the following code on your Terminal:
$ git init
Git will now start to track changes in our project. As git tracks our files, we can see the status of our tracked files and any files that are not tracked by typing the following command:
$ git status
Now we can save our first commit, which is a snapshot of our code at the time that we run the commit command:
# In Bash, comments are marked with a #, just like Python # Add any files that have changes and you wish to save in this # commit
$ git add main.py
# Commit the changes, add in your commit message with -m
$ git commit -m "Our first commit"
Now, at any point in the future, we can return to this point in our project. Adding files that are to be committed is called staging files in Git. Remember that you should only add stage files if you are ready to commit them. Once the files are staged, any further changes will not be staged. For an example of more advanced Git usage, add any text to your main.py file with your text editor and then run the following:
# To see the changes from the last commit
$ git diff
# To see the history of your changes
$ git log
# As an example, we will stage main.py
# and then remove any added files from the stage
$ git add main.py
$ git status
$ git reset HEAD main.py
# After any complicated changes, be sure to run status
# to make sure everything went well
$ git status
# lets delete the changes to main.py, reverting to its state at the
# last commit # This can only be run on files that aren't staged
$ git checkout -- main.py
Your terminal should look something like the following:
Note that in the preceding example I have modified the main.py file by adding the comment # Changed to show the git diff command.
One important step to include in every Git repository is a .gitignore file. This file tells Git what files to ignore. This way you can safely commit and add all your files. The following are some common files that you can ignore:
Python's byte code files (
*.pyc
)
Databases (specially for our examples using SQLLite database files) (
*.db
)
Secrets (never push secrets (password, keys, and so on) to your repositories)
IDE metadata files (
.idea
)
The
Virtualenv
directory (
env
or
venv
)
Here's a simple example of a gitignore file:
*.pyc*.pem*.pub*.tar.gz*.zip*.sql*.dbsecrets.txt./tmp./build/*.idea/*.ideaenvvenv
Now we can safely add all the files to git and commit them:
$ git add --all
$ git status
$ git commit -a -m "Added gitignore and all the projects missing files"
The Git system's checkout command is rather advanced for this simple introduction, but it is used to change the current status of the Git system's HEAD pointer, which refers to the current location of our code in the history of our project. This will be shown in the next example.
Now, if we wish to see the code in a previous commit, we should first run the following command:
$ git log
commit cd88be37f12fb596be743ccba7e8283dd567ac05 (HEAD -> master)
Author: Daniel Gaspar
Date: Sun May 6 16:59:46 2018 +0100
Added gitignore and all the projects missing files
commit beb471198369e64a8ee8f6e602acc97250dce3cd
Author: Daniel Gaspar
Date: Fri May 4 19:06:57 2018 +0100
Our first commit
The string of characters next to our commit message, beb4711, is called the hash of our commit. It is the unique identifier of the commit that we can use to return to the saved state. Now, to take the project back to the previous state, run the following command:
$ git checkout beb4711
Your Git project is now in a special state where any changes or commits will neither be saved nor affect any commits that were made after the one you checked out. This state is just for viewing old code. To return to the normal mode of Git, run the following command:
$ git checkout master
In Python, programmers can download libraries from other programmers that extend the functionality of the standard Python library. As you already know from using Flask, a lot of Python's power comes from its large number of community-created libraries.
However, installing third-party libraries can be a huge pain to do correctly. Say that you want to install package X. Simple enough: download the ZIP file and runsetup.py, right? Not quite. Package X relies on package Y, which in turn relies on Z and Q. None of this information was listed on package X's website, but these packages need to be installed for X to work at all. You then have to find all of the packages one by one and install them, and then hope that the packages you are installing don't require any extra packages themselves.
In order to automate this process, we use pip, the Python package manager.
If you are using Windows, and your previously installed version of Python is the current version, then you already have pip! If your Python installation is not the most recent version, then the easiest thing to do is to simply reinstall it. Download the Python Windows installer at https://www.python.org/downloads/.
In Windows, the variable that controls which programs are accessible from the command line is the path. To modify our path to include Python and pip, we have to add C:\Python27 and C:\Python27\Tools. Edit the Windows path by opening the Windows menu, right-clicking on Computer, and clicking on Properties. Under Advanced system settings, click Environment Variables.... Scroll down until you find Path, double-click on it, and add ;C:\Python27;C:\Python27\Tools to the end.
To make sure that you have modified your path correctly, close and reopen your Terminal and type the following into the command line:
pip --help
Pip should have printed its usage message, as shown in the following screenshot:
Some Python installations of Linux do not come with pip, and Mac OS X's installations doesn't come with pip by default. If you are using Python 2.7, then you may need to install pip, but pip is already included in Python 3.4, and in later versions. You can check this using the following:
$ python3 -m pip list
If you need to install it, download the get-pip.py file from https://bootstrap.pypa.io/get-pip.py.
Once you have downloaded it, run it with elevated privileges using the following code:
# Download and install pip$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py
Once this has been entered, pip will be installed automatically.
We are now going to learn the basic commands for using Python package manager. To install a package with pip, enter the following code:
$ pip install [package-name]
On Mac and Linux, because you are installing programs outside of the user-owned folders, you might have to prepend sudo to the install commands. To install Flask, simply run the following:
$ pip install flask
Once you have done this, all of the requirements that you need for using Flask will be installed for you.
If you want to remove a package that you are no longer using, run the following:
$ pip uninstall [package-name]
If you wish to explore or find a package, but don't know its exact name, you can use the search command:
$ pip search [search-term]
Now that we have a couple of packages installed, it is common courtesy in the Python community to create a list of packages that are required to run the project so that others can quickly install every necessary package. This also has the added benefit that any new member of your project will be able to run your code quickly.
This list can be created with pip by running the following command:
$ pip freeze > requirements.txt
What exactly did this command do? The pip freeze command automatically prints out a list of the installed packages and their versions. For our example, it prints the following:
click==6.7
Flask==0.12.4
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
Werkzeug==0.14.1
The > operator tells Bash to take everything printed by the last command and write it to this file. If you look in your project directory, you can see a new file named requirements.txt that contains the output of pip freeze.
To install all the packages from this file, a new project maintainer would have to run this, as shown in the following code. Normally, this will also be used to deploy the production environment of your project:
$ pip install -r requirements.txt
The preceding code tells pip to read all the packages listed in requirements.txt and install them.
So you have installed all the packages that you want for your new project. Great! But what happens when we develop a second project some time later that will use newer versions of the same packages? And what happens when a library that you wish to use depends on a library that you installed for the first project, but which uses an older version of these packages? When newer versions of packages contain breaking changes, upgrading them would require extra development work on an older project that you may not be able to afford. So in our system, we could have clashing Python packages between projects.
We should also consider automated build environments, such as Jenkins, where we want to run tests. These builds may run on the same system on which other projects are being built, so it's essential that during the build jobs we create a contained Python package environment that is not shared between jobs. This environment is created from the information in therequirements.txt file that we created earlier. This way, multiple Python applications can be built and tested on the same system without clashing with each other.
Thankfully, there is virtualenv, a tool that sandboxes your Python projects. The secret to virtualenv is in tricking your computer to look for and install packages in the project directory rather than in the main Python directory, which allows you to keep them completely separate.
If you're using Python 3—and I recommend that you do, because Python 2 support will end in 2020—then you don't have to install virtualenv; you can use it just by running it like a package, as shown in the following code:
# Create a python 3 virtualenv$ python3 -m venv env
Now that we have pip, if we need to install virtualenv, then we can just run the following command:
$ pip install virtualenv
Let's initialize virtualenv for our project, as follows:
$ virtualenv env
The extra env tells virtualenv to store all the packages in a folder named env. Virtualenv requires you to start it before it will sandbox your project. You can do this using the following code:
$ source env/bin/activate
# Your prompt should now look like
(env) $
The source command tells Bash to run the env/bin/activate script in the context of the current directory. Let's reinstall Flask in our new sandbox, as follows:
# you won't need sudo anymore
(env) $ pip install flask
# To return to the global Python
(env) $ deactivate
Your development projects normally need more then a web server application layer; you will most definitely need some kind of database system. You might be using a cache, redis, workers with Celery, a messaging queuing system, or something else. Normally, all of the systems that are needed for your application to work are collectively referred to as stack. One simple way to easily define and quickly spawn all these components is to use Docker containers. With Docker, you define all of your application components and how to install and configure them, and you can then share your stack with your team, and send it to production with the exact same specification.
You can download and install Docker from https://docs.docker.com/install/.
First, let's create a very simple Dockerfile. This file defines how to set up your application. Each line will serve as a container layer for very fast rebuilds. A very simple Dockerfile will look like the following:
FROM python:3.6.5
# Set the working directory to /app
WORKDIR /app# Copy local contents into the containerADD . /app# Install all required dependenciesRUN pip install -r requirements.txtEXPOSE 5000CMD ["python", "main.py"]
Next, let's build out first container image. We will tag it as chapter_1 for further ease of use, as shown in the following code:
$ docker build -t chapter_1 .
Then we will run it, as shown in the following code:
$ docker run -p 5000:5000 chapter_1# List all the running containers$ docker container list
Docker is easy, but it's a complex tool with lots of options for configuring and deploying containers. We will look at Docker in more detail in Chapter 13, Deploying Flask Apps.
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.
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"
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 darwinApp: main [debug]Instance: /chapter_1/instance
>>> app.url_mapMap([<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
