Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Flask By Example
Flask By Example

Flask By Example: Unleash the full potential of the Flask web framework by creating simple yet powerful web applications

eBook
$26.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Flask By Example

Chapter 1. Hello, World!

And hello, reader! Let's get started with building some Flask applications. Flask is minimalist enough to allow you choice and flexibility; unlike in larger frameworks, you choose what you want to do and then manipulate Flask to do your bidding, and it is complete enough to work right out of the box.

We'll walk together through the development of three web applications; the first one is straightforward and will allow you to cut your teeth on Flask and get used to the new technologies and terminology while building a nontrivial web application; the second will get you started with building a web application that makes use of a traditional SQL database; and the final, which has the most features, will make use of a NoSQL database and a frontend framework to create a useful and good-looking web application.

In this chapter, we'll take a brief look at what Flask is and, perhaps more importantly, what it isn't. We'll move on to setting up our basic development environment as well as a web server, and we'll install a Python package manager as well as Flask itself. By the end of the chapter, we'll have the outlines of our first app, and, as dictated by age-old tradition, we'll use our new skills to display the text "Hello, World!".

In brief, we will cover the following topics:

  • Introducing Flask
  • Creating our development environment
  • Writing "Hello, World!"
  • Deploying our application to production

Introducing Flask

Flask is a micro framework for Python web development. A framework, in the simplest terms, is a library or collection of libraries that aims to solve a part of a generic problem instead of a complete specific one. When building web applications, there are some problems that will always need to be solved, such as routing from URLs to resources, inserting dynamic data into HTML, and interacting with an end user.

Flask is a micro framework because it implements only core functionality (including routing) but leaves more advanced functionality (including authentication and database ORMs) to extensions. The result of this is less initial setup for the first-time user and more choice and flexibility for the experienced user. This is in contrast with "fuller" frameworks, such as Django, which dictate their own ORM and authentication technologies.

As we'll discuss, our Hello World application in Flask can be written in only seven lines of code, with the entire application consisting of a single file. Does that sound good? Let's get going!

Creating our development environment

A development environment consists of all the software that a developer uses while building software. For starters, we'll install a Python package manager (pip) and the Flask package. In this book, we'll show detailed steps for developing using Python 2.7 on a clean installation of Ubuntu 14.04, but everything should be easy to translate to Windows or OS X.

Installing pip

For our Hello World application, we only need the Python Flask package, but we'll install several Python packages throughout the development process of our three applications. To manage these packages, we'll use the Python package manager pip. If you've developed in Python without a package manager until now, you'll love how easy it is to download, install, remove, and update packages using pip. If you already use it, then skip to the next step where we'll use it to install Flask.

The pip manager is included in Python's 3.4+ and 2.7.9+ versions. For older versions of Python, pip needs to be installed. To install pip on Ubuntu, open a terminal and run the following command:

sudo apt-get update
sudo apt-get install python-pip

Note

To install pip on Windows or OS X, you can download and run the get-pip.py file from the pip homepage at https://pip.pypa.io/en/latest/installing/#install-or-upgrade-pip.

That's it! You can now easily install any Python package you need through pip.

Installing Flask

Installing Flask through pip could not be more straightforward. Simply run the following:

pip install –-user flask

You might see some warnings in your terminal, but at the end, you should also see Successfully installed Flask. Now, you can import Flask into a Python program just as with any other library.

Note

If you're used to using VirtualEnv for Python development, you can install Flask inside a VirtualEnv environment. We will discuss this further in Appendix, A Sneak Peek into the Future.

Writing "Hello, World!"

Now, we'll create a basic web page and serve it using Flask's built-in server to localhost. This means that we'll run a web server on our local machine that we can easily make requests to from our local machine. This is very useful for development but not suited for production applications. Later on, we'll take a look at how to serve Flask web applications using the popular Apache web server.

Writing the code

Our application will be a single Python file. Create a directory in your home directory called firstapp and a file inside this called hello.py. In the hello.py file, we'll write code to serve a web page comprising the static string "Hello, World!". The code looks as follows:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(port=5000, debug=True)

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.
  • Hover the mouse pointer on the SUPPORT tab at the top.
  • Click on Code Downloads & Errata.
  • Enter the name of the book in the Search box.
  • Select the book for which you're looking to download the code files.
  • Choose from the drop-down menu where you purchased this book from.
  • Click on Code Download.

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

Let's break down what this does. The first line should be familiar; it simply imports Flask from the package flask. The second line creates an instance of the Flask object using our module's name as a parameter. Flask uses this to resolve resources, and in complex cases, one can use something other than __name__ here. For our purposes, we'll always use __name__, which links our module to the Flask object.

Line 3 is a Python decorator. Flask uses decorators for URL routing, so this line of code means that the function directly below it should be called whenever a user visits the main root page of our web application (which is defined by the single forward slash). If you are not familiar with decorators, these are beautiful Python shortcuts that seem a bit like black magic at first. In essence, they call a function that takes the function defined under the decorator (in our case, index()) and returns a modified function.

The next two lines should also seem familiar. They define a very simple function that returns our message. As this function is called by Flask when a user visits our application, the return value of this will be what is sent in response to a user who requests our landing page.

Line 6 is a Python idiom with which you are probably familiar. This is a simple conditional statement that evaluates to True if our application is run directly. It is used to prevent Python scripts from being unintentionally run when they are imported into other Python files.

The final line kicks off Flask's development server on our local machine. We set it to run on port 5000 (we'll use port 80 for production) and set debug to True, which will help us see detailed errors directly in our web browser.

Running the code

To run our development web server, simply fire up a terminal and run the hello.py file. If you used the same structure outlined in the previous section, the commands will be as follows:

cd firstapp/hello
python hello.py

You should get an output similar to that in the following screenshot:

Running the code

Also, you should see the process continue to run. This is our web server listening for requests. So, let's make a request!

Fire up a web browser—I use Firefox, which comes packaged with Ubuntu—and navigate to localhost:5000.

The localhost part of the URL is a shortcut to the loopback address, usually 127.0.0.1, which asks your computer to make the web request to itself. The number after the colon (5000) is the port it should make the request to. By default, all HTTP (web) traffic is carried over port 80. For now, we'll use 5000 as it is unlikely to conflict with any existing services, but we'll change over to port 80 in production, which is conventional, so that you won't have to worry about the colon.

You should see the "Hello, World!" string displayed in your browser as in the following screenshot. Congratulations, you've built your first web application using Flask!

Running the code

Deploying our application to production

It's great to have an application that runs, but inherent to the idea of a web application is the idea that we want others to be able to use it. As our application is Python-based, we are a bit limited in how we can run our application on a web server (many traditional web hosts are only configured to run PHP and/or .NET applications). Let's consider how to serve Flask applications using a Virtual Private Server (VPS) running Ubuntu Server, Apache, and WSGI.

From this point on, we'll maintain two environments. The first is our development environment, which we just set up and where we'll write code and view its results using the Flask server running on localhost (as we just did). The second will be a production environment. This will be a server to which we can deploy our web applications and make them accessible to the world. When we install new Python libraries or other software on our development environment, we'll normally want to mirror our actions in the production environment.

Setting up a Virtual Private Server

Although you could, in theory, host your web application on your local machine and allow others to use it, this has some severe limitations. First of all, every time you turned off your computer, your app would not be available. Also, your computer probably connects to the Internet via an Internet Service Provider (ISP) and possibly a wireless router. This means that your IP address is dynamic and changes regularly, which makes it difficult for your applications' users to keep up! Finally, chances are that you have an asymmetrical connection to the Internet, which means that your upload speed is slower than your download speed.

Hosting your application on a server solves all of these problems. Before "the cloud" became popular, the traditional way to host a web application was to buy a physical server and find a data center to host it. These days, things are far simpler. In a few minutes, you can fire up a virtual server, which to you seems just like a physical server—you can log in to it, configure it, and enjoy full control over it—but it is actually just a virtual "piece" of a machine owned and controlled by a cloud provider.

At the time of writing, major players in the cloud provider field include Amazon Web Services, Microsoft Azure, Google Cloud Compute, and Digital Ocean. All of these companies allow you to hire a virtual server or servers upon paying by the hour. If you are learning Flask as a hobby and are unwilling to pay anyone to host your web applications, you'll probably find a free trial at one of the providers quite easily. The smallest offering by any provider is fine to host all the applications that we'll run.

Select one of the preceding providers or another of your choosing. If you've never done anything similar before, Digital Ocean is often cited to have the simplest process of signing up and creating a new machine. Once you select a provider, you should be able to follow their respective instructions to fire up a VPS that runs Ubuntu Server 14.04 and SSH into it. You'll have full control over the machine with one slight difference: you won't have a display or a mouse.

You'll enter commands on your local terminal, which will in fact be run on the remote machine. Detailed instructions on how to connect to your VPS will be given by the provider, but if you use Ubuntu, it should be as simple as running the following:

ssh user@123.456.789.000

Alternatively, if you set it up with a public-private key authentication, where yourkey.pem is the full path to your private key file, here's the command to run:

ssh user@123.456.78.000 –i yourkey.pem

Here, user is the default user on the VPS, and yourkey is the name of your private key file.

SSH from other operating systems:

Tip

SSH from OS X should be the same as Ubuntu, but if you're using Windows, you'll have to download PuTTY. Refer to http://www.putty.org/ to download and for full usage instructions. Note that if you use key files for authentication, you'll have to convert them to a format compatible with PuTTY. A conversion tool can also be found on the PuTTY website.

Once we connect to the VPS, installing Flask is the same process as it was previously:

sudo apt-get update
sudo apt-get install python-pip
pip install --user Flask

To install our web server, Apache, and WSGI, we will run the following:

sudo apt-get install apache2
sudo apt-get install libapache2-mod-wsgi

Apache is our web server. It will listen for web requests (which are generated by our users visiting our web application using their browsers) and hand these requests over to our Flask application. As our application is in Python, we also need WSGI (Web Server Gateway Interface).

This is a common interface between web servers and Python applications, which allows Apache to talk to Flask and vice versa. An overview of the architecture can be seen in the following diagram:

Setting up a Virtual Private Server

Configuring our server

Now that we've installed Apache, we can see our first results. You're probably used to visiting websites using a URL, such as http://example.com. We'll access our web applications using the IP address of our VPS directly. Your VPS should have a static public address. Static means that it doesn't change periodically, and public means that it is globally unique. When you connected to the VPS via SSH, you probably used the public IP to do this. If you can't find it, run the following on your VPS and you should see an inet addr section in the output, which contains your public IP:

ifconfig

The IP address should look similar to 123.456.78.9. Enter your IP address into your browser's address bar, and you should see a page saying "Apache2 Ubuntu Default Page: It Works!" or something similar, as in the following screenshot:

Configuring our server

This means that we can now serve web content to anyone with an Internet connection! However, we still have to:

  • Copy our code to the VPS
  • Link up Apache and Flask
  • Configure Apache to serve our Flask application

For the first step, we'll set up a Git repository on our local machine and clone the repository to the VPS. For the second step, we'll use the WSGI module that we installed with Apache. Finally, we'll take a look at how to write a virtual host to have Apache serve our Flask application by default.

Installing and using Git

Git is a version control system. A version control system, among other things, saves multiple versions of our code base automatically. This is great to undo accidental changes or even deletions; we can simply revert to a previous version of our code. It also includes lots of functionality for distributed development—that is, many developers working on a single project. We'll use it mainly for its backup and deployment features, however.

To install Git on your local machine and VPS, run the following commands on each:

sudo apt-get update
sudo apt-get install git

Note

Make sure you're comfortable with the difference between running commands on your own machine using the terminal and on your server through the SSH connection. In many cases, we'll need to run the same commands twice—once for each environment.

Now that you have the software, you need a place to host your Git repositories or "repos". Two popular and free Git hosting services are GitHub (http://github.com) and Bitbucket (http://bitbucket.org). Head over to one of them, create an account, and create a new repository by following the instructions that they provide. When given the option to give your repository a name, call it firstapp to match the name of the directory that we will use for our code base. Once you create a new repository, you should be given a unique URL to your repository. Take note of this as we'll use it to push our Hello, World! application using git and then deploy it to our VPS.

On your local machine, open a terminal and change the directory to the Flask application. Initialize a new repository and link it to your remote Git repository via the following commands:

cd firstapp
git init
git remote add origin <your-git-url>

Tell git who you are, to allow it to automatically add metadata to your code changes, as follows:

git config --global user.email "you@example.com"
git config --global user.name "Your Name"

Git allows you full control over which files are part of your repository and which aren't. Even though we initialized the Git repo in our firstapp directory, our repo currently contains no files. Add our application to the repo, commit, and then push it, as follows:

git add hello.py
git commit -m "Initial commit"
git push -u origin master

These are the main Git commands that we'll use throughout this book, so let's take a brief look at what each does. The add command adds new or modified files to our repository. This tells Git which files are actually part of our project. Think of the commit command as taking a snapshot of our project in its current state. This snapshot is saved on our local machine. It is good to make a new commit with any major change to the code base as we can easily revert to previous commits if a later commit breaks our application. Finally, the push command pushes our local changes to the remote Git server. This is good for backup, and it will also allow us to fetch the changes on our VPS, thus keeping the code base on our local machine and that on our VPS in sync.

Now, SSH into your VPS again and get a copy of our code, as follows:

cd /var/www
git clone <your-git-url>

Note

Where the <your-git-url> part of the above command is actually a placeholder for the URL to your Git repository.

If you get a permission denied error on trying to clone the Git repository, you might need to take ownership of the /var/www directory for the Linux user that you're using. If you logged into the server with tom@123.456.789.123, you can run the following command, which will give your user ownership of /var/www and allow you to clone the Git repository into it. Again tom is the placeholder used in the following case:

sudo chown -R tom /var/www

If you used firstapp as a name for your remote repository, this should create a new directory called firstapp. Let's verify that our code is there using the following:

cd firstapp
ls

You should see your hello.py file. Now, we need to configure Apache to use WSGI.

Serving our Flask app with WSGI

First, we'll create a very straightforward .wsgi file in our application directory. Then, we'll create an Apache configuration file in the directory where Apache looks for available sites.

The only slightly tricky part about these two steps is that we'll create the files directly on our VPS, and as our VPS does not have a display, this means that we have to use command-line interface text editors. Of course, we could create the files locally and then transfer them to our VPS as we did for our code base, but for small changes to configuration files, this is often more effort than it's worth. Using a text editor without a mouse takes a bit of getting used to, but it's a good skill to learn. The default text editor on Ubuntu is Nano, and the other popular choices are vi or Vim. Some people use Emacs. If you already have a favorite, go with it. If not, we'll use Nano for the examples in this book (it is already installed and arguably the simplest to use). However, if you want to go the extra mile, I recommend learning to use Vim.

Assuming you're still connected to your VPS and have navigated to the /var/www/firstapp directory as in the most recent steps, run the following command:

nano hello.wsgi

This creates the hello.wsgi file, which you can now edit through Nano. Type the following:

import sys
sys.path.insert(0, "/var/www/firstapp")
from hello import app as application

This is simply Python syntax, which patches our application into the PATH system so that Apache can find it through WSGI. We will then import app (we named this in our hello.py app with the app = Flask(__name__) line) into the namespace.

Hit Ctrl + X to exit Nano and enter Y when prompted to save the changes.

Now, we'll create an Apache configuration file that points to the .wsgi file we just created, as follows:

cd /etc/apache2/sites-available
nano hello.conf

Note

If you run into permission issues while editing or saving files, you may need to take ownership of the apache2 directory too. Run the following command, substituting the username for your Linux user:

sudo chown –R tom /etc/apache2

In this file, we'll create a configuration for an Apache virtual host. This will allow us to serve multiple sites from a single server, which will be useful later when we want to serve other applications using our single VPS. In Nano, enter the following configuration:

<VirtualHost *>
    ServerName example.com

    WSGIScriptAlias / /var/www/firstapp/hello.wsgi
    WSGIDaemonProcess hello
    <Directory /var/www/firstapp>
       WSGIProcessGroup hello
       WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

This might look quite complicated, but it's actually very straightforward. We will create a virtualhost and specify our domain name, where our .wsgi script is, the name of our application, and who is allowed to access it. We'll discuss domain names in the final chapter, but for now, you can just leave it as example.com because we'll access our application by its IP address.

Note

If you get stuck on this step, the Flask website has a great resource on configuring and troubleshooting Apache configuration. You can find it at http://flask.pocoo.org/docs/0.10/deploying/mod_wsgi/.

Hit Ctrl + X and enter Y when prompted again to save and exit the file. Now, we need to enable the configuration and set it as our default site.

Configuring Apache to serve our Flask application

Apache sites work as follows: there is a sites-available directory (where we created the new virtual host configuration file) and a sites-enabled directory, which contains shortcuts to all the configuration files that we want to be active. By default, you'll see a file in the sites-available directory named 000-default.conf. This is the reason that we saw a default It works Apache page when we first installed Apache. We don't want this anymore; instead, we want to use our application as the default site. Therefore, we'll disable the default Apache site, enable our own, and then restart Apache for the changes to take effect. Run these commands to do this:

sudo a2dissite 000-default.conf
sudo a2ensite hello.conf
sudo service apache2 reload

Note

The required Apache configuration and commands can vary quite a bit based on the platform you're using. If you use Ubuntu Server as recommended, the preceding should all work smoothly. If not, you may need to read up a bit on how to configure Apache for your specific platform.

You should note reloading web server apache2 in the output. If errors are displayed, then you probably misconfigured something in the preceding command. If this is the case, read the error message carefully and go back over the previous steps to take a look at why things didn't work as expected.

To test that everything is working, open a web browser on your local machine and type your IP address into the address bar again. You should see Hello, World! displayed in your browser instead of the default Apache page that we saw before.

If you get Error 500 instead, it means that our application fell over for some reason. Fear not; it's better that you get used to dealing with this error now, when the fix will probably be simple, than later on, when we've added more components that could break or be misconfigured. To find out what went wrong, run the following command on your VPS:

sudo tail –f /var/log/apache2/error.log

The tail command simply outputs the last several lines of the file passed as an argument. The -f is for follow, which means that the output will be updated if the file changes. If you can't immediately work out which lines are indicative of the error we're looking for, visit the site in your web browser on your local machine again, and you'll see the output from the tail command be updated accordingly. The following screenshot shows the output from the tail command when there are no errors; however, if anything goes wrong, you'll see the error output printed among all the info messages.

Configuring Apache to serve our Flask application

Some possible tripping points are incorrectly configured WSGI and Apache files (make sure that your WSGIDaemonProcess and daemon name match, for example) or incorrectly configured Python (you may forget to install Flask on your VPS). If you can't figure out what the error message means, an Internet search for the message (removing the error-specific parts of your app, such as names and paths) will usually point you in the right direction. Failing this, there are strong and very friendly Flask and WSGI communities on Stack Overflow and Google Groups, and there's normally someone willing to help beginners. Remember that if you're having a problem and can't find an existing solution online, don't feel bad for asking; you'll help countless people facing issues similar to yours.

Summary

We got through quite a lot of material in this first chapter! We did some initial setup and house-keeping and then wrote our first web application using Flask. We saw this run locally and then discussed how to use Git to copy our code to a server. We configured our server to serve our application to the public; however, our application is merely a static page that prints the "Hello, World!" string to whoever visits our page. This is not useful to many people and could be achieved more simply using a static HTML page. However, with the extra effort we put in, we now have all the power of Python behind our application; we're just not using it yet!

In the next chapter, we'll discover how to take advantage of Python to make our web applications more useful!

Left arrow icon Right arrow icon

Key benefits

  • The most up-to-date book on Flask on the market
  • Create your own world-class applications and master the art of Flask by unravelling its enigma through this journey
  • This step-by-step tutorial is packed with examples on blending different technologies with Flask to get you up and running

Description

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.

Who is this book for?

Have you looked at PHP and hated the clunky bloated syntax? Or looked at .Net and wished it was more open and flexible? Maybe you’ve tried your hand at GUI libraries in Python and found them hard to use? If your answer to any one of these questions is a yes, then this is just the book for you. It is also intended for people who know the basics of Python and want to learn how to use it to build powerful solutions with a web front-end.

What you will learn

  • Build three web applications from the ground up using the powerful Python micro
  • framework, Flask.
  • Dynamically display data to your viewers, based on their requests
  • Store user and static data in SQL and NoSQL databases and use this data to power
  • your web applications
  • Create a good user experience by combining HTML, CSS, and JavaScript
  • Harness the convenience of freely available APIs, including OpenWeatherMap, Open
  • Exchange Rates, and bitly
  • Extend your applications to build advanced functionality, such as a user account
  • control system using Flask-Login
  • Learn about web application security and defend against common attacks, such as
  • SQL injection and XSS
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 31, 2016
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781785286933
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Mar 31, 2016
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781785286933
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 136.97
Flask By Example
$38.99
Mastering Flask
$48.99
Learning Flask Framework
$48.99
Total $ 136.97 Stars icon

Table of Contents

13 Chapters
1. Hello, World! Chevron down icon Chevron up icon
2. Getting Started with Our Headlines Project Chevron down icon Chevron up icon
3. Using Templates in Our Headlines Project Chevron down icon Chevron up icon
4. User Input for Our Headlines Project Chevron down icon Chevron up icon
5. Improving the User Experience of Our Headlines Project Chevron down icon Chevron up icon
6. Building an Interactive Crime Map Chevron down icon Chevron up icon
7. Adding Google Maps to Our Crime Map Project Chevron down icon Chevron up icon
8. Validating User Input in Our Crime Map Project Chevron down icon Chevron up icon
9. Building a Waiter Caller App Chevron down icon Chevron up icon
10. Template Inheritance and WTForms in Waiter Caller Project Chevron down icon Chevron up icon
11. Using MongoDB with Our Waiter Caller Project Chevron down icon Chevron up icon
A. A Sneak Peek into the Future Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4
(8 Ratings)
5 star 25%
4 star 12.5%
3 star 50%
2 star 0%
1 star 12.5%
Filter icon Filter
Top Reviews

Filter reviews by




Rahul Shelke Apr 05, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"While starting to learn a new framework for web development, it is really important to learn basics of the web development, framework chosen and language in which it is written.""Flask by Example" is one such book where you will start as a novice into flask development and learn step by step through live projects mentioned in book. Starting from first chapter, it will give you basic ideas about how web development works, what are web servers, creating backend functionality using python, creating templates using Jinja 2.0, integrating html, jquery and bootstrap into web application, integrating with MySQL database and MongoDB database, etc. and it will take you to the advanced web development like making code live on aws, using git for source code maintenance, making site live on apache server, etc. Everyone who wants to learn web development into python flask framework, whether you are experienced web developer into some other language or framework OR you are a beginner, will find this book useful to learn.NOTE: I have been a part of this book as technical reviewer, and this review is based on my experience about the content of the book and way it is presented to the readers
Amazon Verified review Amazon
saiello Oct 13, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
So far (into chapter 3), this book does a good job getting up and running learning Flask. The book assumes some knowledge of Linux, for example in my Ubuntu box I wasn't in the right context when installing Python, and Flask and it caused my web server not to run properly.
Amazon Verified review Amazon
Xiaobo Cao Jul 13, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The book explains Flask and a couple of its extensions. The explanation is detailed and clear, and contents covered in this book are useful for starting with building a web site. I personally felt that I learned a lot from it and have mastered the basics to build a Flask website.I really like the three projects used in the book. They really demonstrate lots of common problems and useful tools/ways to tackle them.The only reason I take one star off is because I saw a few typos in the book, both in the text and code. As a book introducing coding, the typo in the code or the text explaining the code will be misleading and takes lots of time for the readers to figure out the error.
Amazon Verified review Amazon
Lawrence Nov 20, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Am only at page 24 of the book and the code there does not work. It only gives list index out of range error around first_article = feed['entries'][0]. How can this be solved?
Amazon Verified review Amazon
Kristin Apr 29, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
First I would like to say for the most up to date book on the market I expected it to be Python 3. I am almost halfway through and have had to adjust a couple of things so far to work with Python3. But so far it's been simple things like changing imported modules. The book is well written and really does a great job of explaining things simply even at the expense of going back and refactoring code to make it more concise. I recommend this book to anyone wanting to learn flask. Only knock so far is not being in python3.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela