Flask By Example - Gareth Dwyer - E-Book

Flask By Example E-Book

Gareth Dwyer

0,0
27,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 378

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Flask By Example
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Hello, World!
Introducing Flask
Creating our development environment
Installing pip
Installing Flask
Writing "Hello, World!"
Writing the code
Running the code
Deploying our application to production
Setting up a Virtual Private Server
Configuring our server
Installing and using Git
Serving our Flask app with WSGI
Configuring Apache to serve our Flask application
Summary
2. Getting Started with Our Headlines Project
Setting up our project and a Git repository
Creating a new Flask application
Introduction to RSS and RSS feeds
Using RSS from Python
URL routing in Flask
Publishing our Headlines application
Summary
3. Using Templates in Our Headlines Project
Introducing Jinja
Basic use of Jinja templates
Rendering a basic template
Passing dynamic data to our template
Displaying dynamic data in our template
Advanced use of Jinja templates
Using Jinja objects
Adding looping logic to our template
Adding hyperlinks to our template
Pushing our code to the server
Summary
4. User Input for Our Headlines Project
Getting user input using HTTP GET
Getting user input using HTTP POST
Creating a branch in Git
Adding POST routes in Flask
Making our HTML form use POST
Reverting our Git repository
Adding weather and currency data
Introducing the OpenWeatherMap API
Signing up with OpenWeatherMap
Retrieving your OpenWeatherMap API key
Parsing JSON with Python
Introducing JSON
Retrieving and parsing JSON in Python
Using our weather code
Displaying the weather data
Allowing the user to customize the city
Adding another search box to our template
Using the user's city search in our Python code
Checking our new functionality
Handling duplicate city names
Currency
Getting an API key for the Open Exchange Rates API
Using the Open Exchange Rates API
Using our currency function
Displaying the currency data in our template
Adding inputs for the user to select currency
Creating an HTML select drop-down element
Adding all the currencies to the select input
Displaying the selected currency in the drop-down input
Summary
5. Improving the User Experience of Our Headlines Project
Adding cookies to our Headlines application
Using cookies with Flask
Setting cookies in Flask
Retrieving cookies in Flask
Writing the fallback logic to check for cookies
Retrieving the cookies for other data
Adding CSS to our Headlines application
External, internal, and inline CSS
Adding our first CSS
Adding padding to our CSS
Adding more styles to our CSS
Adding the div tags to the template file
Styling our inputs
Summary
6. Building an Interactive Crime Map
Setting up a new Git repository
Understanding relational databases
Installing and configuring MySQL on our VPS
Installing MySQL on our VPS
Installing Python drivers for MySQL
Creating our Crime Map database in MySQL
Creating a database setup script
Creating the database
Looking at our table columns
Indexing and committing
Using the database setup script
Adding credentials to our setup script
Running our database setup script
Creating a basic database web application
Setting up our directory structure
Looking at our application code
Looking at our SQL code
Reading data
Inserting data
Deleting data
Creating our view code
Running the code on our VPS
Mitigating against SQL injection
Injecting SQL into our database application
Mitigating against SQL injection
Summary
7. Adding Google Maps to Our Crime Map Project
Running a database application locally
Creating a mock of our database
Adding a test flag
Writing the mock code
Validating our expectations
Adding an embedded Google Maps widget to our application
Adding the map to our template
Introducing JavaScript
The body of our HTML code
Testing and debugging
Making our map interactive
Adding markers
Using a single marker
Adding an input form for new crimes
The HTML code for the form
Adding external CSS to our web application
Creating the CSS file in our directory structure
Adding CSS code
Configuring Flask to use CSS
Viewing the result
Publishing the result
Linking the form to the backend
Setting up the URL to collect POST data
Adding the database methods
Testing the code on the server
Displaying existing crimes on our map
Getting data from SQL
Passing the data to our template
Using the data in our template
Viewing the results
Summary
8. Validating User Input in Our Crime Map Project
Choosing where to validate
Identifying inputs that require validation
Trying out an XSS example
The potential of persistent XSS
Validating and sanitizing
White and blacklisting
Validating versus sanitizing
Implementing validation
Validating the category
Validating the location
Validating the date
Validating the description
Summary
9. Building a Waiter Caller App
Setting up a new Git repository
Setting up the new project locally
Setting up the project on our VPS
Using Bootstrap to kick-start our application
Introducing Bootstrap
Downloading Bootstrap
Bootstrap templates
Adding user account control to our application
Introducing Flask-Login
Installing and importing Flask-Login
Using Flask extensions
Adding a restricted route
Authenticating a user
Creating a user class
Mocking our database for users
Logging in a user
Adding imports and configuration
Adding the login functionality
Writing the login function
Creating the load_user function
Checking the login functionality
Logging out a user
Registering a user
Managing passwords with cryptographic hashes
Python hashlib
Reversing hashes
Salting passwords
Implementing secure password storage in Python
Creating the PasswordHelper class
Updating our database code
Updating our application code
Summary
10. Template Inheritance and WTForms in Waiter Caller Project
Adding the Account and Dashboard pages
Introducing Jinja templates
Creating the base template
Creating the dashboard template
Creating the account template
Creating the home template
Adding the routing code
Creating restaurant tables
Writing the restaurant table code
Adding the create table form
Adding the create table route
Adding the create table database code
Adding the view table database code
Modifying the account route to pass table data
Modifying the template to show the tables
Adding the delete table route to our backend code
Testing the restaurant table code
Shortening URLs using the bitly API
Introducing Bitly
Using the bitly API
Getting a bitly oauth token
Creating the bitlyhelper file
Using the bitly module
Adding functionality to handle attention requests
Writing the attention request code
Adding the attention request route
Adding the attention request database code
Add the get and delete methods for attention requests
Modifying the dashboard route to use attention requests
Modifying the template code to display attention requests
Adding the resolve request application code
Testing the attention request code
Auto-refreshing the dashboard page
Adding user feedback with WTForms
Introducing WTForms
Installing Flask-WTF
Creating the registration form
Rendering the registration form
Updating the application code
Updating the template code
Testing the new form
Using WTForms in our application code
Displaying errors to our user
Displaying the errors in our template
Adding CSS for the errors
Testing the final registration form
Adding a successful registration notification
Passing the message from the application code
Using the message in the template code
Modifying the login form
Creating the new LoginForm in the application code
Using the new LoginForm in the template
Modifying the create table form
Summary
11. Using MongoDB with Our Waiter Caller Project
Introducing MongoDB
Installing MongoDB
Using the MongoDB shell
Starting the MongoDB shell
Running commands in the MongoDB shell
Creating data with MongoDB
Reading data with MongoDB
Updating data with MongoDB
Deleting data with MongoDB
Introducing PyMongo
Writing the DBHelper class
Adding the user methods
Adding the table methods
Adding the request methods
Changing the application code
Testing our application in production
Adding some finishing touches
Adding indices to MongoDB
Where do we add indices?
Adding a favicon
Summary
A. A Sneak Peek into the Future
Expanding the projects
Adding a domain name
Adding HTTPS
E-mail confirmation for new registrations
Google Analytics
Scalability
Expanding your Flask knowledge
VirtualEnv
Flask Blueprints
Flask extensions
Flask-SQLAlchemy
Flask MongoDB extensions
Flask-MongoAlchemy
Flask-PyMongo
Flask-MongoEngine
Flask-Mail
Flask-Security
Other Flask extensions
Expanding your web development knowledge
Summary
Index

Flask By Example

Flask By Example

Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: March 2016

Production reference: 1220316

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-693-3

www.packtpub.com

Credits

Author

Gareth Dwyer

Reviewers

Burhan Khalid

Kyle Roux

Rahul Shelke

Commissioning Editor

Julian Ursell

Acquisition Editor

Kevin Colaco

Content Development Editor

Kajal Thapar

Technical Editors

Kunal Chaudhari

Ravikiran Pise

Copy Editors

Shruti Iyer

Sonia Mathur

Project Coordinator

Shweta H Birwatkar

Proofreader

Safis Editing

Indexer

Rekha Nair

Graphics

Disha Haria

Production Coordinator

Melwyn D'sa

Cover Work

Melwyn D'sa

About the Author

Gareth Dwyer first heard the phrase, "behind every no-entry sign there is a door," a couple of decades ago, and he has been looking for a counterexample ever since. He hasn't found one yet. Gareth grew up with his three siblings in Grahamstown, South Africa. There wasn't much there except some highly respected schools and a small university. Gareth had heard that school was an unpleasant and largely pointless experience, so he opted to skip it and go to the university instead. The university door had a no-entry sign on the door because it only accepted people who had gone to school. Gareth ignored the sign. He studied piano for a while but soon, he wondered if there was more to life than sitting in front of a keyboard all day. So he switched from piano to computer science, and it took him a while to realize the irony. He studied philosophy too because it was here that people never told him to stop being so argumentative.

Gareth noticed the disparagement that his philosophy and computer science departments felt towards each other, and he found it strange. He soon discovered that he wasn't the first person to see that there was room for some common ground, and he went to Europe to study computational linguistics, where he found other people who liked debating the finer points of language while talking about the three hardest problems of computer science (naming things, and off-by-one errors).

In between doodling on blank paper while listening to very knowledgeable people lecture on content that was occasionally fascinating but often soporific, Gareth has gained so-called "industry" experience with companies such as Amazon Web Services in Cape Town and MWR InfoSecurity in Johannesburg. He has several years' experience in writing, and his favorite languages are English and Python.

He discovered that writing and writing a book are not fully overlapping experiences, and the former is hardly preparation for the latter. The pages that follow would not have come into existence without the combined efforts of many people.

Acknowledgements

Thank you Neeshma and Kajal; you have been so very kind and patient in spite of my disrespect for deadlines. Your feedback on each chapter while I was writing and your suggestions that I try to keep to schedule have been invaluable. Thank you to everyone else at Packt Publishing who has been involved in this book, from its idea, through editing, through layout, through marketing, and all the nitty-gritty parts that the reader will never think about. I'm looking forward to the next one already.

Thank you Alisa for listening, even when I complained about writing, and even when I was still complaining a year later.

Thank you Theresa, Stephanie, and Lewis for ensuring I don't go completely sane.

Thank you to all the lecturers and tutors at Rhodes University who contributed to what I know and who I am.

Thank you Ron for teaching me how to string words together, and how commas work, and why some sentences sound nice and others don't.

Finally, thank you Mom and Dad for teaching me everything else.

About the Reviewers

Burhan Khalid has always been tinkering with technology, from his early days on the XT to writing JCL on the ISPF editor, and from C and C++, Java, Pascal, and COBOL to his latest favorite, Python. As a lover of technology, he is most comfortable experimenting with the next big technology stack.

By day, he works in a multinational bank in the Alternative Channels unit, where he gets to hack on, develop, and test applications that help execute transactions across all manner of electronic devices and channels. In addition to his work, he also contributes to open source projects, having released a few toolkits for transaction processing, and he offers consultancy services to startups on their technology stacks and development processes.

He is an avid volunteer; he is a mentor for Sirdab Lab (a startup accelerator), a frequent speaker at the local Google Developer's Group, a presenter and volunteer at StartupQ8 (a startup community), and an active user on StackOverflow.

You can reach him on Twitter @burhan

I would like to thank my mother and father for always encouraging me, my wife for putting up with my long days at the keyboard and my ever-growing gadget collection, and my friends and colleagues for providing me with new challenges to sharpen my skills.

Rahul Shelke is a cofounder of My Cute Office Pvt. Ltd. and Qpeka Technologies Pvt. Ltd. He also acts as an adviser for two other startups, and he helps startups in their growth.

Prior to starting his own venture, Rahul worked with Blisstering solutions for more than two years as a senior developer.

He is an MTech in computer science. His practical experience for the last five years has been in web development, cloud computing, business intelligence, system performance optimization, and software architecture design and development.

He has been actively involved in open source contributions since graduation, and he has contributed to Python, Python-Flask, and Drupal.

First, I would like to thank the Packt Publishing team, Shweta H. Birwatkar, and Gareth Dwyer, for giving me the opportunity to be a part of this project.

A special thanks to My Cute Office team whose support helped me manage work along with this book review. I would also like to thank my family for supporting me during this process.

Finally, thanks to the countless support from Python-Flask's open source community for providing me with such an easy and fast web development framework.

www.PacktPub.com

eBooks, discount offers, and more

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

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

To Ron Hall, who taught me how to write

Preface

In theory, nothing works, but everyone knows why. In practice, everything works but no one knows why. Here, we combine theory and practice; nothing works and no one knows why!

Learning computer science must always be a combination of theory and practice; you need to know what you're doing (theory), but you also need to know how to do it (practice). My experience of learning how to create web applications was that few teachers found a sweet spot for this balance; either I read pages and pages about inheritance, virtual environments, and test-driven development, wondering how it all applied to me, or I installed a bunch of tools and frameworks and libraries and watched the magic happen with no idea how it worked.

What follows is, I hope, a good balance. From the first chapter, you'll have a Flask web application running that the whole world can visit, which is quite practical even if it doesn't do anything but greet visitors with "Hello, World!". In the chapters that follow, we'll walk through building three interesting and useful projects together. In general, we'll build things ourselves wherever possible. While it's not good to reinvent the wheel, it is good to be exposed to a problem before you're exposed to the solution. Learning a CSS framework before you write a single line of CSS leaves you in a confused state, in which you would wonder, "But why do I actually need this?", and the same goes for many other frameworks and tools. So, we'll start from scratch, take a look at why it's difficult, and then introduce tools to make our lives easier. I think this is the ideal balance between theory and practice.

When I told people I was writing a book on Flask, the common response was "Why? There are already so many books and tutorials on Flask." This is a valid question, and the answer to it provides a nice outline for what to expect from this book. Flask By Example is different from other Flask educational material and here's why.

We won't leave you stranded

Many Flask tutorials show you how to develop a Flask application and run it locally on your own machine, and then they end. This is great as a first step, but if you're interested in building web applications, you probably want them to be accessible on the Web so that your friends, family, coworkers, and customers can admire your handiwork without popping by your house. From our first project onward, our applications will run on a Virtual Private Server (VPS) and be accessible to the world.

We won't build a blogging application

If you've read any web application development tutorials, you must have noticed that nearly every one of them is about how to build a blog using x and y. I'm pretty tired of the blog example (actually, I never want to see anyone show me how to build a blog again). Instead, you'll create some interesting, original, and possibly even useful projects while learning how to develop web applications with Flask.

We will focus on security

Cybercrime has become something of a buzzword of late. Arguably, the reason that we read about major web applications being hacked on an almost daily basis is because so many developers do not know about SQL Injection, CSRF, XSS, how to store passwords, and so many other things that should really be considered basic knowledge. As we develop the three projects in this book, we'll take the time to explain some core security concepts in detail and show you how to harden our applications against potentially malicious attackers.

We will give in-depth explanations

We won't just give you some code and tell you to run it. Wherever possible, we will explain what we're doing, why we're doing it, and how we're doing it. This means that you'll be able to take ideas from all of the projects, combine them with your own ideas, and get started with building original content right after working through this book.

Therefore, I hope that this book will be of use to you, no matter whether you are beginning to cut your teeth in the world of computer science and programming or have a computer science degree from a famous university and have compiler theory pouring out of your ears but now want to build something practical and fun. May you have as much fun working through the projects as I did while putting them together!

What this book covers

Chapter 1, Hello, World!, teaches you to set up our development environment and a web server and write our first Flask application.

Chapter 2, Getting Started with Our Headlines Project, shows you how to run Python code when the user visits a URL and how to return basic data to the user. We will also look at fetching the latest headlines automatically using RSS feeds.

Chapter 3, Using Templates in Our Headlines Project, introduces Jinja templates and integrates them into our Headlines project. We will show how to serve dynamic HTML content by passing data from our Python code to template files.

Chapter 4, User Input for Our Headlines Project, shows how to get input from our users over the Internet and use this input to customize what we will show our users. We will look at how to access currenct weather information through JSON APIs and include this information in our Headlines project.

Chapter 5, Improving the User Experience of Our Headlines Project, instructs you to add cookies to our Headlines project so that our application can remember our users' choices. We will also style our application by adding some basic CSS.

Chapter 6, Building an Interactive Crime Map, introduces our new project, which is a crime map. We will introduce relational databases, install MySQL on our server, and look at how to interact with our database from our Flask application.

Chapter 7, Adding Google Maps to our Crime Map Project, instructs you on adding a Google Maps widget and shows how to add and remove markers from the map based on our database. We will add an HTML form with various inputs for users to submit new crimes and also display the existing crimes.

Chapter 8, Validating User Input in Our Crime Map Project, polishes off our second project by making sure that users can't break it accidentally or through maliciously crafted input.

Chapter 9, Building a Waiter Caller App, introduces our final project, which is an application to call a waiter to the table at a restaurant. We will introduce Bootstrap and set up a basic User Account Control system that uses Bootstrap as the frontend.

Chapter 10, Template Inheritance and WTForms in Waiter Caller Project, introduces Jinja's template inheritance features so that we can add similar pages without duplicating code. We will use the WTForms library to make our web forms easier to build and validate.

Chapter 11, Using MongoDB with Our Waiter Caller Project, discusses how to install and configure MongoDB on our server and links it to our Waiter Caller project. We will finish off our final project by adding indices to our database and a favicon to our application.

Appendix, A Sneak Peek into the Future, outlines some important topics and technologies that we weren't able to cover in detail and gives pointers on where more can be learned about these.

What you need for this book

All the examples we will use assume that you use the Ubuntu operating system on your development machine and that you have access to a server that runs Ubuntu Server (we will discuss how to set the latter up in the first chapter). If you strongly prefer another operating system and already have a Python environment set up (including the Python package manger pip), then the examples will be easily translatable.

All other software and libraries used in the book are freely available, and we will demonstrate how to install and configure them in detail as the need arises.

Who this book is for

Have you looked at PHP and hated the clunky bloated syntax? Or, have you looked at .Net and wished that it was more open and flexible? Have you tried your hand at GUI libraries in Python and found them hard to use? If your answer to any one of these questions is 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 frontend.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

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 WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/FlaskByExample_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

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 FlaskCreating our development environmentWriting "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 updatesudo 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.

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 aproduction 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:

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 [email protected] –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 updatesudo apt-get install python-pippip install --user Flask

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

sudo apt-get install apache2sudo 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:

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:

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 VPSLink up Apache and FlaskConfigure 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