Mastering Flask Web Development
eBook - ePub

Mastering Flask Web Development

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

Daniel Gaspar, Jack Stouffer

Condividi libro
  1. 332 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Mastering Flask Web Development

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

Daniel Gaspar, Jack Stouffer

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Mastering Flask Web Development è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Mastering Flask Web Development di Daniel Gaspar, Jack Stouffer in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in Python. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788999557
Edizione
2

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...

Indice dei contenuti