Book Image

Flask By Example

By : Gareth Dwyer
Book Image

Flask By Example

By: Gareth Dwyer

Overview of this book

This book will take you on a journey from learning about web development using Flask to building fully functional web applications. In the first major project, we develop a dynamic Headlines application that displays the latest news headlines along with up-to-date currency and weather information. In project two, we build a Crime Map application that is backed by a MySQL database, allowing users to submit information on and the location of crimes in order to plot danger zones and other crime trends within an area. In the final project, we combine Flask with more modern technologies, such as Twitter's Bootstrap and the NoSQL database MongoDB, to create a Waiter Caller application that allows restaurant patrons to easily call a waiter to their table. This pragmatic tutorial will keep you engaged as you learn the crux of Flask by working on challenging real-world applications.
Table of Contents (20 chapters)
Flask By Example
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Preface
Index

Expanding the projects


The projects we built are all functional, but they are not quite ready for heavy, real-time use. If they were to be built out to handle thousands of users or were commercial applications, they would need a few more features. These are discussed in the following sections.

Adding a domain name

We accessed all of our projects using the IP address of our VPS. You're almost certainly used to visiting web applications using domain names rather than IP addresses. When you use a domain name, such as http://google.com, your browser first sends off a request to a DNS server to find out what the IP address associated with this domain is. DNS servers are similar to huge automatic telephone books that exist solely to translate the domain names that humans find easier to remember (such as http://google.com) in than the IP addresses that organize the Internet (for example, 123.456.789.123).

To use a domain name instead of the IP address, you need to purchase one from a registrar. Often your Internet Service Provider (ISP) can assist you with purchasing a domain name (such as yourname.com). Domain names are normally fairly inexpensive, and you can get them for as little as a few dollars a year.

Once you purchase a domain name, you need to set up the DNS settings correctly. Most ISPs have an online control panel where you can do this yourself, but you may have to contact them to assist you. Your domain needs to point to your VPS. To do this, you create an "A" type DNS record that maps the domain to your IP.

Once your domain name points at your server, you can configure Apache to recognize it by using it instead of our example.com placeholder that we put in the Apache configuration files, such as /etc/apache2/sites-available/waitercaller.conf.

Changes to domain names also take a while to propagate—that is, the major DNS servers of the world need to be updated so that when someone visits your domain name, the DNS server can redirect them to your IP address. DNS propagation can take hours.

Adding HTTPS

You've probably noticed that banks, large corporations such as Google and Microsoft, and an ever-growing number of other companies, have their websites automatically redirect to an HTTPS version. The "S" stands for secure, so the full acronym becomes Hyper Text Transport Protocol Secure. Whenever you see HTTPS in your browser's navigation bar (normally with a green padlock next to it) it means that all traffic flowing between you and the server is encrypted. This prevents so-called man in the middle attacks, where a malicious person between you and the server can view or modify the content that you and the server exchange.

Until recently, this encryption was achieved by the site owner by purchasing an expensive certificate from Certificate Authority (CA). CA's job is to act as a trusted third party between you and the server, issuing a signed certificate to the owner of a site. This certificate can be used to set up an encrypted channel between the client and the server. Because of the prohibitive cost, HTTPS was only used where security was absolutely necessary (for example, in online banking) and by companies such as Google who could afford the high fees. With everyone beginning to realize that the trust-based model of World Wide Web is inherently flawed, HTTPS is becoming more and more popular even for small blogs and personal websites. Companies such as Let's Encrypt (https://letsencrypt.org) are now offering certificates for free and these certificates can easily be installed and configured to work with popular web servers, such as Apache.

For our final project, as we are handling sensitive data (specifically passwords), using HTTPS is a must for nontrivial usage of our application, and it's also desirable for our other two projects (HTTPS is always better than HTTP). Although the process of setting up certificates to work with your web server is far simpler now than it was a couple of years ago, a full walk-through of how to set up Apache2 to play with a CA certificate is beyond the scope of this book.

However, if you only take the time to learn about one of the technologies mentioned in this chapter, then it should be this one. Here is a link to a very simple Digital Ocean tutorial that shows you how to set up the certificate on Ubuntu 14.04 to work with Apache2 (the exact configuration we used in this book):

https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-14-04

E-mail confirmation for new registrations

You probably noted in our third project that our registration process was a little bit unusual. The normal way for new users to register on a site is as follows:

  1. User fills out registration form and submits it.

  2. Server saves the data in the database.

  3. Server generates a unique and secure token and stores the token associated with the registration, which it marks as incomplete.

  4. Server e-mails the token to the user in the form of a URL and requests that the user click on the URL to confirm the account.

  5. User clicks on URL with the unique token.

  6. Server finds an incomplete registration associated with this token and marks the registration as confirmed.

The preceding process is in order to prove that the user gave us a real e-mail address to which he or she has access. Of course, the user does not want to wait for someone to manually send an e-mail, so the confirmation e-mail has to be sent automatically. This leads to a few complications, including the need to set up a mail server and the fact that the automatic confirmation e-mail we send may well end up in the user's spam folder, leading to frustration all round. Another option is to use an E-mail as a service platform, such as Amazon's Simple E-mail Service (SES). However, these are not usually free.

Once the user has a confirmed e-mail account, we can also use it to allow the user to reset a forgotten password. Again, this would involve sending an automatic e-mail to users who wanted to reset their password. The e-mail would again contain a secure unique token in a URL that the user would click on to prove that he or she really did make the password reset request. We would then allow the user to type in a new password and update the database with the new (hashed and salted) password. Note that we can't and shouldn't send the user his or her own password because we store only the salted and hashed version of the password; we have no way of discovering the forgotten one.

The complete user account system with automatic e-mail confirmations and the "forgot your password" functionality is fairly complex. We could set it up using nothing but Python and Flask and an e-mail server, but in the next section, we'll also discuss some more Flask extensions that could make this process easier.

Google Analytics

If we run any of the web applications commercially, we'll probably be interested in how many people actually use them. This would help us in deciding how (and whether) to monetize our applications and provide other useful insights.

The most common way to achieve this is through Google Analytics. This is a service from Google to track not only how many people visit your site but also how long they spend on it, how they found it, their country, information about the device they use for web browsing, and many other insightful statistics. Google Analytics is free, and to get started with using it, you need to simply create an account on https://analytics.google.com (or use your existing Google account). After filling in some information about your site, you'll be given a short snippet of JavaScript. This JavaScript code contains a unique tracking ID assigned to your site. You need to add the JavaScript code to your site, and whenever anyone visits the site, the JavaScript code will be loaded into their web browser and will send information about them to Google, which will then use the unique ID to associate the information with you. On the Google Analytics dashboard, you can then see graphs of the number of visitors, the length of their visits, and many more pieces of information.

In the case of our waiter-caller project, we'd add the JavaScript at the end of the base.html file along with the Bootstrap JavaScript code.

Scalability

The best problem to have as a web application creator is having made an application that is too popular. If lots of people are visiting your application, it means that you created something good (and you can possible start charging people money for it). Our little VPS will not handle a lot of traffic. If thousands of people visit the site simultaneously, we'll run out of network bandwidth, processing capacity, memory, and disk space very quickly.

A complete discussion on creating scalable web applications would be a book all on its own. However, some of the steps we would need to take would be:

  • Run the database on a dedicated machine: At the moment, we run our web server and database on the same physical machine. For a larger web application, the database would have its own dedicated machine so that heavy database use (for instance, many restaurant patrons creating new requests) wouldn't have a negative impact on the people who just wanted to browse our home page. Normally, the database machine would have lots of disk space and memory, while the machine running the web server would focus more on having high bandwidth availability and processing power.

  • Run a load balancer: If we have a lot of visitors, one machine will not be able to keep up with the load no matter how big and powerful the machine is. We would therefore run several duplicate web server machines. The problem would then be to evenly distribute new visitors among all the different machines. To solve this, we would use something called a load balancer, which is responsible for nothing but accepting the initial request from the user (that is, when the user visits your homepage) and assigning this user to one of the replica web servers.

As we grow bigger, the situation would grow more and more complicated, and we would add replica database machines as well. A popular site requires full-time maintenance, often by a team of people, because hardware fails, malicious users exist, and updates (which are necessary to mitigate attacks by malicious users) tend to break the compatibility between software. On the bright side, if any web applications were to grow popular enough to warrant the preceding, the application would probably also generate enough revenue to make all the issues discussed an "SEP", or somebody else's problem. That is, we could hire a system's administrator, a database administrator, and a chief security officer, tell them to sort it out, and spend the rest of our days on ocean cruises. On this note, let's take a look at some Flask-specific expansions to our knowledge.