Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering Flask
Mastering Flask

Mastering Flask: Gain expertise in Flask to create dynamic and powerful web applications

By Jack Stouffer
$48.99
Book Sep 2015 288 pages 1st Edition
eBook
$39.99 $27.98
Print
$48.99
Subscription
$15.99 Monthly
eBook
$39.99 $27.98
Print
$48.99
Subscription
$15.99 Monthly

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
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
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Mastering Flask

Chapter 1. Getting Started

Python is a flexible language that gives programmers the freedom to structure their programming environment. However, a dangerous consequence of this freedom is the ability to not set up a new Python project right from the beginning in order to avoid problems down the road.

For example, you could be halfway through your project and realize that you deleted a file or piece of code five days ago that you need to use now. Consider another example where two of the packages that you wish to use require different versions of the same underlying package. Other than the tools introduced in this chapter, there will be a lot of extra work fixing problems that already have solutions. A little extra work in the beginning can save days of work in the future.

To this end, we will need to install three programs: Git, pip, and virtualenv.

Version control with Git


To protect our project against human error, we will use a version control system called Git. Version control is a tool that records changes in files over time. This allows a programmer to see how the code has changed from previous revisions and even revert the code to the previous state. Version control systems also make collaboration easier than ever, as changes can be shared between many different programmers and merged into the current version of the project automatically, without copying and pasting hundreds of lines of code.

Simply put, version control is like backups for your code, only more powerful.

Installing Git

Installing Git is very simple. Simply go to http://www.git-scm.com/downloads and click on the Operating System (OS) that is being run. A program will begin to download that will walk you through the basic installation process.

Git on Windows

Git was originally developed solely for Unix OSes (for example, Linux, Mac OS X). Consequently, using Git on Windows is not seamless. During the installation, the installer will ask whether you want to install Git alongside the normal Windows Command Prompt. Do not pick this option. Choose the default option that will install a new type of command line on your system named Bash, which is the same command line the Unix systems use. Bash is much more powerful than the default Windows command line, and this will be used in all the examples in this book.

Note

A good introduction to Bash for beginners is located at http://linuxcommand.org/learning_the_shell.php#contents.

Git basics

Git is a very complex tool; only the basics that are needed for this book will be covered here.

Note

To learn more, refer to the Git documentation at http://www.git-scm.com/doc.

Git does not track your changes automatically. In order for Git to run properly, we have to give it the following information:

  • Which folders to track

  • When to save the state of the code

  • What to track and what not to

Before we can do anything, we tell Git to create a git instance in our directory. In your project directory, run the following in your terminal:

$ git init

Git will now start to track changes in our project. As git tracks our files, we can see the status of our tracked files, and any files that are not tracked, by typing the following command:

$ git status

Now we can save our first commit, which is a snapshot of your code at the time that you run the commit command.

# In Bash, comments are marked with a #, just like Python
# Add any files that have changes and you wish to save in this commit
$ git add main.py
# Commit the changes, add in your commit message with -m
$ git commit -m"Our first commit"

At any point in the future, we can return to this point in our project. Adding files to be committed is called staging files in Git. Remember to add stage files only if you are ready to commit them. Once the files are staged, any further changes will not be staged as well. For an example of more advanced Git usage, add any text to your main.py file with your text editor and then run the following:

# To see the changes from the last commit
$ git diff
# To see the history of your changes
$ git log
# As an example, we will stage main.py
# and then remove any added files from the stage
$ git add main.py
$ git status
$ git reset HEAD main.py
# After any complicated changes, be sure to run status
# to make sure everything went well
$ git status
# lets delete the changes to main.py, reverting to its state at the last commit
# This can only be run on files that aren't staged
$ git checkout -- main.py

Your terminal should look something like this:

The Git system's checkout command is rather advanced for this simple introduction, but it is used to change the current status of the Git system's HEAD pointer—that is, the current location of our code in the history of our project. This will be shown in the next example.

Now, to see the code in a previous commit, first run this:

$ git log
Fri Jan 23 19:16:43 2015 -0500 f01d1e2 Our first commit  [Jack Stouffer]

The string of characters next to our commit message, f01d1e2, is called the hash of our commit. It is the unique identifier of that commit that we can use to return to the saved state. Now, to take the project back to that state, run this:

$ git checkout f01d1e2

Your Git project is now in a special state where any changes or commits will neither be saved nor affect any commits that were made after the one you checked out. This state is just for viewing old code. To return to the normal mode of Git, run this:

$ git checkout master

Python package management with pip


In Python, programmers can download libraries from other programmers that extend the functionality of the standard Python library. As you already know from using Flask, a lot of Python's power comes from its large amount of community-created libraries.

However, installing third-party libraries can be a huge pain to do correctly. Say there is a package X that you wish to install. Simple enough, download the Zip file and run setup.py, right? Not quite. Package X relies on package Y, which in turn relies on Z and Q. None of this information was listed on package X's website, but they are required to be installed for X to work at all. You then have to find all of the packages one by one and install them, in the hope that the packages you are installing don't require any extra packages themselves.

In order to automate this process, we use pip, the Python package manager.

Installing the pip Python package manager on Windows

If you are on Windows, and your installed Python the current version, you already have pip! If your Python installation is not the most recent, the easiest thing to do is to simply reinstall it. Download the Python Windows installer at https://www.python.org/downloads/.

In Windows, the variable that controls which programs are accessible from the command line is path. To modify your path to include Python and pip, we have to add C:\Python27 and C:\Python27\Tools. Edit the Windows path by opening the Windows menu, right-clicking on Computer and clicking on Properties. Under Advanced system settings, click Environment Variables.... Scroll down until you find Path, double-click it, and add ;C:\Python27;C:\Python27\Tools to the end.

To make sure you have modified your path correctly, close and reopen your terminal and type the following into the command line:

pip --help

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.

pip should have printed its usage message as shown in the following screenshot:

Installing the pip Python package manager on Mac OS X and Linux

Some Python installations of Linux do not come with pip, and Mac OS X installations don't come with pip by default. To install it, download the get-pip.py file from https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py.

Once you have downloaded it, run it with elevated privileges using the following:

$ sudo python get-pip.py

Then pip will be installed automatically.

pip basics

To install a package with pip, follow this simple step:

$ pip install [package-name]

On Mac and Linux, because you are installing programs outside the user-owned folders, you might have to prepend sudo to the install commands. To install Flask, simply run this:

$ pip install flask

Then, all requirements of Flask will be installed for you.

If you want to remove a package that you are no longer using, run this:

$ pip uninstall [package-name]

If you wish to explore or find a package but don't know its exact name, you may use the search command:

$ pip search [search-term]

Now that we have a couple of packages installed, it is common courtesy in the Python community to create a list of packages that are required to run the project, so others can quickly install every thing required. This also has the added benefit that any new member of your project will be able to run your code quickly.

This list can be created with pip by running this:

$ pip freeze > requirements.txt

What exactly did this command do? pip freeze run by itself prints out a list of the installed packages and their versions as follows:

Flask==0.10.1
itsdangerous==0.24
Jinja2==2.7.3
MarkupSafe==0.23
Werkzeug==0.10.4
wheel==0.24.0

The > operator tells Bash to take everything printed by the last command and write it to this file. If you look into your project directory, you will see the new file named requirements.txt that contains the output of pip freeze.

To install all the packages from this file, a new project maintainer will have to run this:

$ pip install -r requirements.txt

This tells pip to read all the packages listed in requirements.txt and install them.

Dependency sandboxing with virtualenv


So you have installed all the packages you want for your new project. Great! But, what happens when we develop the second project some time later that will use newer versions of the same packages? What happens when a library that you wish to use depends on a library you installed for the first project, but it uses an older version? When newer versions of packages contain breaking changes, upgrading them will require extra development work on an older project that you may not be able to afford.

Thankfully, there is virtualenv, a tool that sandboxes your Python projects. The secret to virtualenv is tricking your computer into looking for and installing packages in the project directory rather than in the main Python directory, which allows you to keep them completely separate.

Now that we have pip, to install virtualenv just run this:

$ pip install virtualenv

virtualenv basics

Let's initialize virtualenv for our project as follows:

$ virtualenv env

The extra env tells virtualenv to store all the packages into a folder named env. virtualenv requires you to start it before it will sandbox your project:

$ source env/bin/activate
# Your prompt should now look like
(env) $

The source command tells Bash to run the script env/bin/activate in the context of the current directory. Let's reinstall Flask in our new sandbox as follows:

# you won't need sudo anymore
(env) $ pip install flask
# To return to the global Python
(env) $ deactivate

However, it goes against the best practices in Git to track what you don't own, so we should avoid tracking the changes in third-party packages. To ignore specific files in our project, the gitignore file is needed.

$ touch .gitignore

touch is the Bash command to create files, and the dot at the start of a file tells Bash to not list its existence unless specifically told to show hidden files. We will create the simple gitignore file for now:

env/
*.pyc

This tells Git to ignore the entire env directory and ignore all the files that end with .pyc (a compiled Python file). When used in this way, the * character is called a wildcard.

The beginning of our project


Finally, we can get to our first Flask project. In order to have a complex project at the end of the book, we will need a simple Flask project to start us off.

In the file named config.py, add the following:

class Config(object):
    pass

class ProdConfig(Config):
    pass

class DevConfig(Config):
    DEBUG = True

Now, in another file named main.py, add the following:

from flask import Flask
from config import DevConfig

app = Flask(__name__)
app.config.from_object(DevConfig)

@app.route('/')
def home():
    return '<h1>Hello World!</h1>'

if __name__ == '__main__':
    app.run()

For anyone who is familiar with the base Flask API, this program is very basic. It will just show Hello World! on the browser if we navigate to http://127.0.0.1:5000/. One point that may be unfamiliar to Flask users is config.from_object, rather than app.config['DEBUG']. We use from_object because in future, multiple configurations will be used, and manually changing every variable when we need to switch between configurations is tedious.

Remember to commit these changes in Git:

# The --all flag will tell git to stage all changes you have made
# including deletions and new files
$ git add --all
$ git commit -m "created the base application"

Note

Reminders will no longer be given on when to commit your changes to Git. It is up to readers to develop the habit of committing whenever you reach a stopping point. It is also assumed that you will be operating inside the virtual environment, so all command line prompts will not be prefixed with (env).

Using Flask Script

In order to make next chapters easier for the reader, we will use the first of many Flask extensions (packages that extend the functionality of Flask) named Flask Script. Flask Script allows programmers to create commands that act within the Application Context of Flask—that is, the state in Flask that allows modification of the Flask object. Flask Script comes with some default commands to run the server and a python shell in the Application Context. To install Flask Script with pip, run this:

$ pip install flask-script

We will cover more advanced usage of Flask Script in Chapter 10, Useful Flask Extensions; for now, let's start with a simple script named manage.py. First import Flask Script's objects and your app as follows:

from flask.ext.script import Manager, Server
from main import app

Then, pass your app to the Manager object, which will initialize Flask Script:

manager = Manager(app)

Now we add our commands. The server is the same as the normal development server run through main.py. The make_shell_context function will create a Python shell that can be run within the app context. The returned dictionary will tell Flask Script what to import by default:

manager.add_command("server", Server())

@manager.shell
def make_shell_context():
    return dict(app=app)

Note

Running the shell through manage.py will become necessary later on when the Flask extensions will only initialize when a Flask app is created. Running the default Python shell will cause these extensions to return errors.

Then, end the file with the Python standard way of running only if the user ran this file:

if __name__ == "__main__":
    manager.run()

You will now be able to run the development server with:

$ python manage.py server

Use the shell with:

$ python manage.py shell
# Lets check if our app imported correctly
>>> app
<Flask 'main'>

Summary


Now that we have set up our development environment, we can move on to implementing advanced application features in Flask. Before we can do anything visual, we need something to display. In the next chapter, you will be introduced to, and then master working with, databases in Flask.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Work with scalable Flask application structures to create complex web apps
  • • Discover the most powerful Flask extensions and learn how to create one
  • • Deploy your application to real-world platforms using this step-by-step guide
  • s

Description

Starting from a simple Flask app, this book will walk through advanced topics while providing practical examples of the lessons learned. After building a simple Flask app, a proper app structure is demonstrated by transforming the app to use a Model-View-Controller (MVC) architecture. With a scalable structure in hand, the next chapters use Flask extensions to provide extra functionality to the app, including user login and registration, NoSQL querying, a REST API, an admin interface, and more. Next, you’ll discover how to use unit testing to take the guesswork away from making sure the code is performing as it should. The book closes with a discussion of the different platforms that are available to deploy a Flask app on, the pros and cons of each one, and how to deploy on each one.

What you will learn

• Set up a best practices Python environment • Use SQLAlchemy to programmatically query a database • Develop templates in Jinja • Set up an MVC environment for Flask • Discover NoSQL, when to use it, when not to, and how to use it • Develop a custom Flask extension • Use Celery to create asynchronous tasks
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 : Sep 30, 2015
Length 288 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781784393656
Category :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
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
Buy Now
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 : Sep 30, 2015
Length 288 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781784393656
Category :

Table of Contents

20 Chapters
Mastering Flask Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Getting Started Chevron down icon Chevron up icon
2. Creating Models with SQLAlchemy Chevron down icon Chevron up icon
3. Creating Views with Templates Chevron down icon Chevron up icon
4. Creating Controllers with Blueprints Chevron down icon Chevron up icon
5. Advanced Application Structure Chevron down icon Chevron up icon
6. Securing Your App Chevron down icon Chevron up icon
7. Using NoSQL with Flask Chevron down icon Chevron up icon
8. Building RESTful APIs Chevron down icon Chevron up icon
9. Creating Asynchronous Tasks with Celery Chevron down icon Chevron up icon
10. Useful Flask Extensions Chevron down icon Chevron up icon
11. Building Your Own Extension Chevron down icon Chevron up icon
12. Testing Flask Apps Chevron down icon Chevron up icon
13. Deploying Flask Apps Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

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