Flask Blueprints 1st Edition Joel Perras instant download
Flask Blueprints 1st Edition Joel Perras instant download
download
https://ebookname.com/product/flask-blueprints-1st-edition-joel-
perras/
https://ebookname.com/product/node-js-blueprints-tsonev/
https://ebookname.com/product/elasticsearch-blueprints-1st-
edition-vineeth-mohan/
https://ebookname.com/product/arduino-android-blueprints-1st-
edition-schwartz/
https://ebookname.com/product/democracy-and-the-rule-of-law-in-
classical-athens-essays-on-law-society-and-politics-edward-m-
harris/
Portugal 18th ed Edition Darwin Porter
https://ebookname.com/product/portugal-18th-ed-edition-darwin-
porter/
https://ebookname.com/product/introduction-to-biomedical-
engineering-2nd-ed-edition-john-enderle/
https://ebookname.com/product/the-knowing-organization-how-
organizations-use-information-to-construct-meaning-create-
knowledge-and-make-decisions-2nd-edition-chun-wei-choo/
https://ebookname.com/product/inuksuit-silent-messengers-of-the-
arctic-1st-pbk-ed-edition-hallendy/
https://ebookname.com/product/fate-and-free-will-a-defense-of-
theological-determinism-heath-white/
Renewables Information 2004 Edition Oecd
https://ebookname.com/product/renewables-
information-2004-edition-oecd/
Flask Blueprints
Joël Perras
BIRMINGHAM - MUMBAI
Flask Blueprints
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.
ISBN 978-1-78439-478-3
www.packtpub.com
Credits
Reviewers Proofreader
Shalabh Aggarwal Safis Editing
Christoph Heer
Andreas Porevopoulos Indexer
Monica Ajmera Mehta
Commissioning Editor
Julian Ursell Graphics
Disha Haria
Acquisition Editor
Meeta Rajani Production Coordinator
Nilesh R. Mohite
Technical Editor
Bharat Patil
Copy Editor
Tasneem Fatehi
About the Author
Currently, his days are spent building infrastructure and Python applications with
the incredible people at Fictive Kin, writing open source code, and trying to lift
heavy weights over his head on a regular basis.
I'd like to thank Sara for her infinite patience throughout the
process of writing this lengthy technical manual and my coworkers
at Fictive Kin for dealing with my particularly bad sense of humor
on a daily basis.
About the Reviewers
The agile practices that he uses for all his developing/deploying needs are Git,
Ansible, Vagrant, and Docker.
www.PacktPub.com
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 service@packtpub.com 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.
TM
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 Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
[ ii ]
Table of Contents
[ iii ]
Preface
The setting is familiar enough: you're a web developer who has worked with a
few programming languages, frameworks and environments, and decided to learn
enough Python to make a few toy web applications. Maybe you've already used
some Python web frameworks to build an application or two, and want to explore a
few of the alternative options that you keep hearing about.
As a microframework, Flask is built to help you and then get out of your way.
Taking a very different approach from most other general-purpose web frameworks,
Flask consists of a very small core that handles the processing and normalization
of HTTP and the WSGI specification (via Werkzeug) and provides an exceptionally
good templating language (via Jinja2). The beauty of Flask lies in its intrinsic
extensibility: as it was designed from the start to do very little, it was also designed
to be extended very easily. A pleasant consequence of this is that you are not
beholden to a particular database abstraction layer, authentication protocol, or
caching mechanism.
Learning a new framework is not simply about learning the basic functions and
objects that are provided to you: it's often as important to learn how the framework
can be adapted to help you build the specific requirements of your application.
This book will demonstrate how to develop a series of web application projects with
the Python web microframework, and leverage extensions and external Python
libraries/APIs to extend the development of a variety of larger and more complex
web applications.
[v]
Preface
Chapter 2, Small to Big – Growing the Flask Application Structure, explores the various
baseline layouts and configurations that you might consider for a Flask application.
The pros and cons of each approach are outlined as we progress from the simplest one-
file application structure to the more complex, multipackage Blueprint architecture.
Chapter 3, Snap – the Code Snippet Sharing Application, builds our first simple
Flask application centered around learning the basics of one of the most popular
relational database abstractions, SQLAlchemy, and several of the most popular Flask
extensions: Flask-Login to handle authenticated user login sessions, Flask-Bcrypt
to ensure that account passwords are stored in a secure manner, and Flask-WTF to
create and process form-based input data.
Chapter 4, Socializer – the Testable Timeline, builds a very simple data model for a
social web application where the main focus is on unit and functional testing using
pytest, the Python testing framework and tools. We will also explore the use of
the application factory pattern, which allows us to instantiate separate versions of
our application for the purposes of simplifying testing. Additionally, the use and
creation of often-omitted (and forgotten) signals, provided by the Blinker library, are
described in detail.
[ vi ]
Preface
Chapter 6, Hublot – Flask CLI Tools, covers a topic that is often omitted from most web
application framework discussions: command-line tools. The use of Flask-Script is
explained, and several CLI-based tools are created to interact with the data models
of our application. Additionally, we will build our very own custom Flask extension
that wraps an existing Python library to fetch the repository and issue information
from the GitHub API.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
[ vii ]
Preface
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"This will create a blank app1 environment and activate it. You should see an (app1)
tag in your shell prompt."
{% endblock %}
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
from application.users.views import users
app.register_blueprint(users, url_prefix='/users')
# …
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Then it
asserts that the Sign up! button text appears in the returned HTML".
[ viii ]
Preface
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.
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 on 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.
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 would 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 on our website, or added to any list
of existing errata, under the Errata section of that title. Any existing errata can be
viewed by selecting your title from http://www.packtpub.com/support.
[ ix ]
Preface
Piracy
Piracy of copyright 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.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.
Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.
[x]
Starting on the Right
Foot – Using Virtualenv
One of the great difficulties in modern software development is that of dependency
management. Generally, a dependency of a software project consists of a library or
component that is required for the project to function correctly. In the case of a Flask
application (and more generally, that of a Python application), most dependencies
are comprised of specially organized and annotated source files. Once created,
these packages of source files may then be included in other projects and so forth.
For some, this chain of dependencies can become an unmanageable mess, where
the slightest alteration to any of the libraries in the chain can cause a cascade of
incompatibilities that would bring further development to a screeching halt. In
the Python world, as you may know already, the fundamental unit of a reusable
set of source files is that of a Python module (a file that contains definitions and
statements). Once you've created a module on your local filesystem and ensured
that it is in your system's PYTHONPATH, including it in a newly created project
is as simple as specifying the import, which is as follows:
import the_custom_module
[1]
Starting on the Right Foot – Using Virtualenv
This is not where the story ends, of course. While modules littering your local
filesystem might be convenient at first, what happens when you want to share some
of the code that you've written for others? Usually, this would entail emailing/
Dropboxing the files in question, however, this is obviously a very cumbersome
and error-prone solution. Thankfully, this is a problem that has been considered
and some progress has been made in alleviating the common issues. The most
significant of these advances is the subject of this chapter, and how the following
techniques for creating reusable, isolated packages of code can be leveraged to ease
the development of a Flask application:
In this chapter, when we refer to a package, what we will actually be talking about
would be succinctly described as a distribution—a bundle of software to be installed
from a remote source—and not a collection of modules in a folder structure that
utilizes the__init__.py convention in order to delineate the folders containing the
modules that we want to be importable.
Most of the distributions of a modern Python version will come with setuptools
already installed. If it is not present on your system of choice, then obtaining it is
relatively simple, with additional instructions available on the official documentation:
wget https://bootstrap.pypa.io/ez_setup.py -O - | python
[2]
Chapter 1
setup(
name="My Great Project",
version="0.0.1",
author="Jane Doe",
author_email="jane@example.com",
description= "A brief summary of the project.",
license="BSD",
keywords="example tutorial flask",
url="http://example.com/my-great-project",
packages=['foobar','tests'],
long_description="A much longer project description.",
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
Once the package has been created, most developers will choose to upload
their newly minted package to PyPI—the official source of nearly all Python
packages—using the built-in tools that are provided by setuptools itself. While the
use of this particular public PyPI repository is not a requirement (it's even possible
to set up your own personal package index), most Python developers will expect to
find their packages here.
This brings us to one more essential piece of the puzzle—the pip Python package
installer. If you have Python 2.7.9 or greater installed, then pip will already be
present. Some distributions might have it preinstalled for you or it might be present
in a system-level package. For a Debian-like distribution of Linux, it may be installed
via the following command:
apt-get install python-pip
[3]
Starting on the Right Foot – Using Virtualenv
Pip is a tool for installing Python packages (and is itself a Python package). While it
is not the only player in the game, pip is by far the most widely used.
One can invoke pip in the command line to install, say, a scientific computing
package on the local filesystem:
$ pip install numpy
The preceding command will query the default PyPI index for a package named
numpy and download the latest version to a special place in your system, usually /
usr/local/lib/pythonX.Y/site-packages (X and Y are the major/minor versions
of the Python version that pip points to). This operation may require root privileges
and would thus require sudo or similar actions to allow it to be completed.
One of the many benefits of virtual environments, which we will explore shortly,
is that they generally avoid the privilege escalation requirement that can plague
system-level changes to installed packages.
Once this operation is completed successfully, you now have the ability to import
the numpy package into new modules and use any and all of the functionalities that
it exposes:
import numpy
x = numpy.array([1, 2, 3])
sum = numpy.sum(x)
print sum # prints 6
[4]
Chapter 1
Once we have this package (or any other, for that matter) installed, there's nothing
stopping us from fetching additional packages in the usual way. Moreover, we can
install multiple packages at the same time by providing their names as additional
arguments to the install command:
$ pip install scipy pandas # etc.
The Python ecosystem has come up with a solution to the basic issues that arise from
what is colloquially referred to as dependency hell. While far from perfect, it allows
developers to sidestep many of the simplest package version dependency conflicts
that can arise in web application development.
It creates an environment that has its own installation directories, that doesn't
share libraries with other virtualenv environments (and optionally doesn't access
the globally installed libraries either).
[5]
Starting on the Right Foot – Using Virtualenv
More concisely, virtualenv allows you to create isolated environments for each one
of your Python applications (or any Python code).
In Python 3.3+, a mostly API-compatible version of the virtualenv tool was added
to the default language packages. The name of the module is venv, however, the
name of the script that allows you to create a virtual environment is pyvenv and can
be invoked in a similar way as the previously discussed virtualenv tool, as follows:
$ mkdir -p ~/envs
$ pyvenv ~/envs/testing
[6]
Another Random Document on
Scribd Without Any Related Topics
‘Free Labour’ (i. e. dared to prohibit soul-murder on the part of the
rich, and self-slaughter on that of the poor!), or any dictum of our
grave law authorities from Fortescue—to Eldon: for from the
borough of Hell I wish to have no representatives.” Henry Crabb
Robinson’s Diary, ii. 93-95.
[167] James Maitland, 1759-1839, eighth Earl of Lauderdale,
belonged to the party of Charles James Fox, and, like Coleridge,
opposed the first war with France, which began in 1793. In the
ministry of “All the Talents” he held the Great Seal of Scotland.
Coleridge calls him plebeian because he inherited the peerage from
a remote connection. He was the author of several treatises on
finance and political economy.
[168] It was, I have been told by an eyewitness, Coleridge’s habit to
take a pinch of snuff, and whilst he was talking to rub it between his
fingers. He wasted so much snuff in the process that the maid
servant had directions to sweep up these literary remains and
replace them in the canister.
[169] A pet name for the Gillmans’ younger son, Henry.
[170] Coleridge was fond of quoting these lines as applicable to
himself.
[171] Washington Allston.
[172] Charles Robert Leslie, historical painter, 1794-1859, was born
of American parents, but studied art in London under Washington
Allston. A pencil sketch, for which Coleridge sat to him in 1820, is in
my possession. Mr. Hamo Thornycroft, R. A., after a careful
inspection of other portraits and engravings of S. T. Coleridge,
modelled the bust which now (thanks to American generosity) finds
its place in Poets’ Corner, mainly in accordance with this sketch.
[173] Letters, Conversations, and Recollections of S. T. Coleridge,
London, 1836, i. 1-3.
[174] The Prospectus of the Lectures on the History of Philosophy
was printed in Allsop’s Letters, etc., as Letter xliv., November 26,
1818, but the announcement of the time and place has been
omitted. A very rare copy of the original prospectus, which has been
placed in my hands by Mrs. Henry Watson, gives the following
details:—
“This course will be comprised in Fourteen Lectures, to commence
on Monday evening, December 7, 1818, at eight o’clock, at the
Crown and Anchor, Strand; and be continued on the following
Mondays, with the intermission of Christmas week—Double Tickets,
admitting a Lady and Gentleman, Three Guineas. Single Tickets, Two
Guineas. Admission to a Single Lecture, Five Shillings. An Historical
and Chronological Guide to the course will be printed.”
A reporter was hired at the expense of Hookham Frere to take down
the lectures in shorthand. A transcript, which I possess, contains
numerous errors and omissions, but is interesting as affording proof
of the conversational style of Coleridge’s lectures. See, for further
account of Lectures of 1819, Samuel Taylor Coleridge, a Narrative,
by J. Dykes Campbell, pp. 238, 239.
[175] Thomas Phillips, R. A., 1770-1845, painted two portraits of
Coleridge, one of which is in the possession of Mr. John Murray, and
was engraved as the frontispiece of the first volume of the Table
Talk; and the other in that of Mr. William Rennell Coleridge, of
Salston, Ottery St. Mary. The late Lord Chief Justice used to say that
the Salston picture was “the best presentation of the outward man.”
No doubt it recalled his great-uncle as he remembered him. It
certainly bears a close resemblance to the portraits of Coleridge’s
brothers, Edward and George, and of other members of the family.
[176] My impression is that this letter was written to Mrs. Aders, the
beautiful and accomplished daughter of the engraver Raphael Smith,
but the address is wanting and I cannot speak with any certainty.
[177] Compare lines 16-20 of The Two Founts:—
“As on the driving cloud the shiny bow,
That gracious thing made up of tears and light.”
The theme was selected by Boyer for insertion in his Liber Aureus of
school exercises in prose and verse, now in the possession of James
Boyer, Esq., of the Coopers’ Company. The sentence to which
Coleridge alludes ran thus: “As if we were in some great sea-vortex,
every moment we perceive our ruin more clearly, every moment we
are impelled towards it with greater force.”
The essay was printed for the first time in the Illustrated London
News, April 1, 1893.
[220] This letter, which is addressed in Coleridge’s handwriting, “Mrs.
Aders, favoured by H. Gillman,” and endorsed in pencil, “S. T. C.’s
letter for Miss Denman,” refers to the new edition of his poetical
works which Coleridge had begun to see through the press.
Apparently he had intended that the “Epitaph” should be inscribed
on the outline of a headstone, and that this should illustrate, by way
of vignette, the last page of the volume.
[221] Of the exact date of Sterling’s first visit to Highgate there is no
record. It may, however, be taken for granted that his intimacy with
Coleridge began in 1828, when he was in his twenty-third year, and
continued until the autumn of 1833,—perhaps lasted until
Coleridge’s death. Unlike Maurice, and Maurice’s disciple, Kingsley,
Sterling outlived his early enthusiasm for Coleridge and his
acceptance of his teaching. It may be said, indeed, that, thanks to
the genius of his second master, Carlyle, he suggests both the
reaction against and the rejection of Coleridge. Of that rejection
Carlyle, in his Life of Sterling, made himself the mouth-piece. It is
idle to say of that marvellous but disillusioning presentment that it is
untruthful, or exaggerated, or unkind. It is a sketch from the life,
and who can doubt that it is lifelike? But other eyes saw another
Coleridge who held them entranced. To them he was the seer of the
vision beautiful, the “priest of invisible rites behind the veil of the
senses,” and to their ears his voice was of one who brought good
tidings of reconciliation and assurance. Many, too, who cared for
none of these things, were attracted to the man. Like the wedding-
guest in the Ancient Mariner, they stood still. No other, they felt, was
so wise, so loveable. They, too, were eye-witnesses, and their
portraiture has not been outpainted by Carlyle. Apart from any
expression of opinion, it is worth while to note that Carlyle saw
Coleridge for the last time in the spring of 1825, and that the Life of
Sterling was composed more than a quarter of a century later. His
opinion of the man had, indeed, changed but little, as the notes and
letters of 1824-25 clearly testify, but his criticism of the writer was
far less appreciative than it had been in Coleridge’s lifetime. The
following extracts from a letter of Sterling to Gillman, dated
“Hurstmonceaux, October 9, 1834,” are evidence that his feelings
towards Coleridge were at that time those of a reverent disciple:—
“The Inscription [in Highgate Church] will forever be enough to put
to shame the heartless vanity of a thousand such writers as the
Opium Eater. As a portrait, or even as a hint for one, his papers
seem to me worse than useless.
“If it is possible, I will certainly go to Highgate, and wait on Mrs.
Gillman and yourself. I have travelled the road thither with keen and
buoyant expectation, and returned with high and animating
remembrances oftener than any other in England. Hereafter, too, it
will not have lost its charm. There is not only all this world of
recollection, but the dwelling of those who best knew and best loved
his work.” Life of Sterling, 1871, pp. 46-54; Samuel Taylor Coleridge,
a Narrative, by J. Dykes Campbell, pp. 259-261; British Museum,
add. MS. 34,225, f. 194.
[222] The following unpublished lines were addressed by Coleridge
to this young lady, a neighbour, I presume, and friend of the
Gillmans. They must be among the last he ever wrote:—
ELISA.
Translation of Claudian.
Imitation.
Sweet Gift! and always doth Eliza send
Sweet Gifts and full of fragrance to her Friend.
Enough for Him to know they come from Her,
Whate’er she sends is Frankincense and Myrrh.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com