Mastering Flask Web Development
eBook - ePub

Mastering Flask Web Development

Build enterprise-grade, scalable Python web applications, 2nd Edition

Daniel Gaspar, Jack Stouffer

Share book
  1. 332 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Mastering Flask Web Development

Build enterprise-grade, scalable Python web applications, 2nd Edition

Daniel Gaspar, Jack Stouffer

Book details
Book preview
Table of contents
Citations

About This Book

Learn to build modern, secure, highly available web MVC applications and API's using Python`s Flask framework.

Key Features

  • Create production-ready MVC and REST API with the dynamic features of Flask
  • Utilize the various extensions like Flask-JWT and Flask-SQLAlchemy to develop powerful applications
  • Deploy your flask application on real-world platforms like AWS and Heroku on VM's or Docker containers

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

  • Develop a Flask extension using best practices
  • Implement various authentication methods: LDAP, JWT, Database, OAuth, and OpenID
  • Learn how to develop role-based access security and become an expert on Jinja2 templates
  • Build tests for your applications and APIs
  • Install and configure a distributed task queue using Celery and RabbitMQ
  • Develop RESTful APIs and secure REST API's
  • Deploy highly available applications that scale on Heroku and AWS using Docker or VMs

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.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Mastering Flask Web Development an online PDF/ePUB?
Yes, you can access Mastering Flask Web Development by Daniel Gaspar, Jack Stouffer in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Python. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788999557

Deploying Flask Apps

Now that we have reached the last chapter of the book, and have a fully functioning web app made in Flask, the final step in our development cycle is to make the app available for the world. There are many different approaches for hosting your Flask app, each of them with its own pros and cons. This chapter will cover the best solutions and guide you through situations in which you should choose one over the other.
In this chapter, we will cover the following:
  • A brief introduction to the most commonly used web servers and gateway interfaces
  • How to deploy on various cloud services
  • How to build Docker images
  • How to describe services using Docker compose
  • How to describe your infrastructure using AWS CloudFormation (IaC)
  • How to set up and work with a CI/CD system to easily build, test, review, and deploy our application

Web servers and gateway interfaces

In this section, we will make a quick introduction to the most commonly used web servers and Web Server Gateway Interfaces (WSGI), and their differences and configuration. A WSGI is an application-agnostic layer between the web server and the python application itself.

Gevent

The simplest option to get a web server up and running is to use a Python library, named gevent, to host your application. Gevent is a Python library that adds an alternative way of doing concurrent programming,called co-routines, outside of the Python threading library. Gevent has an interface to run WSGI applications that is both simple and has good performance. A simple gevent server can easily handle hundreds of concurrent users, which is 99% more than the users of websites on the internet will ever have. The downside to this option is that its simplicity means a lack of configuration options. There is no way, for example, to add rate limiting to the server, or to add HTTPS traffic. This deployment option is purely for sites that you don't expect to receive a huge amount of traffic. Remember YAGNI: only upgrade to a different web server if you really need to.
Co-routines are a bit outside of the scope of this book, but a good explanation can be found at https://en.wikipedia.org/wiki/Coroutine.
To install gevent, we will use pip with the following command:
 $ pip install gevent
In the root of the project directory, in a new file named gserver.py, add the following:
 from gevent.wsgi import WSGIServer from webapp import create_app app = create_app('webapp.config.ProdConfig') server = WSGIServer(('', 80), app) server.serve_forever()
To run the server with supervisor, just change the command value to the following:
 [program:webapp] command=python gserver.py  directory=/home/deploy/webapp user=deploy
Now when you deploy, gevent will automatically be installed for you by running your requirements.txt on every deployment; that is, if you are properly pip freezing after every new dependency is added.

Tornado

Tornado is another very simple way to deploy WSGI apps purely with Python. Tornado is a web server that is designed to handle thousands of simultaneous connections. If your application needs real-time data, Tornado also supports WebSockets for continuous, long-lived connections to the server.
Do not use Tornado in production on a Windows server. The Windows version of Tornado is not only slower—it is also considered beta-stage quality software.
To use Tornado with our application, we will use Tornado's WSGIContainer in order to wrap the application object to make it Tornado-compatible. Then, Tornado will start to listen on port 80 for requests until the process is terminated. In a new file, named tserver.py, add the following:
 from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from webapp import create_app app = WSGIContainer(create_app("webapp.config.ProdConfig")) http_server = HTTPServer(app) http_server.listen(80) IOLoop.instance().start()
To run the Tornado with supervisor privileges, just change the command value to the following:
 [program:webapp] command=python tserver.py  directory=/home/deploy/webapp user=deploy

Nginx and uWSGI

If you need better performance or more options for customization, the most popular way to deploy a Python web application is to use a Nginx web server as a frontend for the WSGI-based uWSGI server by using a reverse proxy. A reverse proxy is a program in networks that retrieves contents for a client from a server, as if it returned from the proxy itself. This process is shown in the following diagram:
Nginx and uWSGI are used like this, because this way, we get the power of the Nginx frontend, while having the customization of uWSGI.
Nginx is a very powerful web server that became popular by providing the best combination of speed and customization. Nginx is consistently faster than other web severs, such as Apache's httpd, and has native support for WSGI applications. It achieves this speed thanks to the developers taking several good architecture decisions, as well as not going to try to cover a large amount of use cases, as Apache does. The latter point here was a decision taken early on in development of Nginx. Having a smaller feature set makes it much easier to maintain and optimize the code. From a programmer's perspective, it is also much easier to configure Nginx, as there is no giant default configuration file (httpd.conf) that can be overridden with .htaccess files in each of your project directories.
uWSGI is a web server that supports several different types of server interfaces, including WSGI. uWSGI handles the severing of the application content, as well as things such as the load balancing of traffic across several different processes and threads.
To install uWSGI, we will use a pip command, as follows:
 $ pip install uwsgi
In order to run our application, uWSGI needs a file with an accessible WSGI application. In a file named wsgi.py in the top level of the project directory.
To test uWSGI, we can run it from the command-line interface (CLI) with the following commands:
 $ uwsgi --socket 127.0.0.1:8080  --wsgi-file wsgi.py  --callable app  --processes 4  --threads 2 
If you are running this on your server, you should be able to access port 8080 and see your app (if you don't have a firewall, that is).
What this command does is load the app object from the wsgi.py file, and make it accessible from localhost on port 8080. It also spawns four different processes with two threads each, which are automatically load balanced by a master proce...

Table of contents