Flask Web Development Developing Web Applications with Python 1st Edition Miguel Grinberg instant download
Flask Web Development Developing Web Applications with Python 1st Edition Miguel Grinberg instant download
https://ebookfinal.com/download/flask-web-development-developing-
web-applications-with-python-1st-edition-miguel-grinberg/
https://ebookfinal.com/download/flask-web-development-1st-edition-
miguel-grinberg/
https://ebookfinal.com/download/developing-responsive-web-
applications-with-ajax-and-jquery-1st-edition-sandeep-kumar-patel/
https://ebookfinal.com/download/web-scraping-with-python-collecting-
data-from-the-modern-web-1st-edition-ryan-mitchell/
https://ebookfinal.com/download/developing-web-applications-with-
visual-basic-net-and-asp-net-1st-edition-john-alexander/
Web Engineering The Discipline of Systematic Development
of Web Applications Gerti Kappel
https://ebookfinal.com/download/web-engineering-the-discipline-of-
systematic-development-of-web-applications-gerti-kappel/
https://ebookfinal.com/download/web-development-with-jade-1st-edition-
sean-lang/
https://ebookfinal.com/download/enjoying-web-development-with-
tapestry-1st-edition-ka/
https://ebookfinal.com/download/building-web-applications-with-erlang-
working-with-rest-and-web-sockets-on-yaws-1st-edition-zachary-kessin/
https://ebookfinal.com/download/web-development-with-the-mac-1st-
edition-aaron-vegh/
Flask Web Development Developing Web Applications
with Python 1st Edition Miguel Grinberg Digital Instant
Download
Author(s): Miguel Grinberg
ISBN(s): 9781449372620, 1449372627
Edition: 1
File Details: PDF, 8.44 MB
Year: 2014
Language: english
Flask Web Development
Miguel Grinberg
Flask Web Development
by Miguel Grinberg
Copyright © 2014 Miguel Grinberg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected].
Editors: Meghan Blanchette and Rachel Roumeliotis Cover Designer: Randy Comer
Production Editor: Nicole Shelby Interior Designer: David Futato
Copyeditor: Nancy Kotary Illustrator: Rebecca Demarest
Proofreader: Charles Roumeliotis
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Flask Web Development, the picture of a Pyrenean Mastiff, and related trade dress are trademarks
of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-37262-0
[LSI]
For Alicia.
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
3. Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
The Jinja2 Template Engine 22
Rendering Templates 22
Variables 23
Control Structures 24
Twitter Bootstrap Integration with Flask-Bootstrap 26
Custom Error Pages 29
Links 31
v
Static Files 32
Localization of Dates and Times with Flask-Moment 33
4. Web Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Cross-Site Request Forgery (CSRF) Protection 37
Form Classes 38
HTML Rendering of Forms 40
Form Handling in View Functions 41
Redirects and User Sessions 44
Message Flashing 46
5. Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
SQL Databases 49
NoSQL Databases 50
SQL or NoSQL? 51
Python Database Frameworks 51
Database Management with Flask-SQLAlchemy 52
Model Definition 54
Relationships 56
Database Operations 57
Creating the Tables 58
Inserting Rows 58
Modifying Rows 60
Deleting Rows 60
Querying Rows 60
Database Use in View Functions 62
Integration with the Python Shell 63
Database Migrations with Flask-Migrate 64
Creating a Migration Repository 64
Creating a Migration Script 65
Upgrading the Database 66
6. Email. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Email Support with Flask-Mail 69
Sending Email from the Python Shell 70
Integrating Emails with the Application 71
Sending Asynchronous Email 72
vi | Table of Contents
Using an Application Factory 78
Implementing Application Functionality in a Blueprint 79
Launch Script 81
Requirements File 82
Unit Tests 83
Database Setup 85
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Table of Contents | ix
Preface
Flask stands out from other frameworks because it lets developers take the driver’s seat
and have full creative control of their applications. Maybe you have heard the phrase
“fighting the framework” before. This happens with most frameworks when you decide
to solve a problem with a solution that isn’t the official one. It could be that you want to
use a different database engine, or maybe a different method of authenticating users.
Deviating from the path set by the framework’s developers will give you lots of
headaches.
Flask is not like that. Do you like relational databases? Great. Flask supports them all.
Maybe you prefer a NoSQL database? No problem at all. Flask works with them too.
Want to use your own homegrown database engine? Don’t need a database at all? Still
fine. With Flask you can choose the components of your application or even write your
own if that is what you want. No questions asked!
The key to this freedom is that Flask was designed from the start to be extended. It comes
with a robust core that includes the basic functionality that all web applications need
and expects the rest to be provided by some of the many third-party extensions in the
ecosystem and, of course, by you.
In this book I present my workflow for developing web applications with Flask. I don’t
claim to have the only true way to build applications with this framework. You should
take my choices as recommendations and not as gospel.
Most software development books provide small and focused code examples that
demonstrate the different features of the target technology in isolation, leaving the “glue”
code that is necessary to transform these different features into a fully working appli‐
cations to be figured out by the reader. I take a completely different approach. All the
examples I present are part of a single application that starts out very simple and is
expanded in each successive chapter. This application begins life with just a few lines of
code and ends as a nicely featured blogging and social networking application.
xi
Who This Book Is For
You should have some level of Python coding experience to make the most of this book.
Although the book assumes no previous Flask knowledge, Python concepts such as
packages, modules, functions, decorators, and object-oriented programming are as‐
sumed to be well understood. Some familiarity with exceptions and diagnosing issues
from stack traces will be very useful.
While working through the examples in this book, you will spend a great deal of time
in the command line. You should feel comfortable using the command line of your
operating system.
Modern web applications cannot avoid the use of HTML, CSS, and JavaScript. The
example application that is developed throughout the book obviously makes use of
these, but the book itself does not go into a lot of detail regarding these technologies
and how they are used. Some degree of familiarity with these languages is recommended
if you intend to develop complete applications without the help of a developer versed
in client-side techniques.
I released the companion application to this book as open source on GitHub. Although
GitHub makes it possible to download applications as regular ZIP or TAR files, I strongly
recommend that you install a Git client and familiarize yourself with source code version
control, at least with the basic commands to clone and check out the different versions
of the application directly from the repository. The short list of commands that you’ll
need is shown in “How to Work with the Example Code ” on page xiii. You will want to
use version control for your own projects as well, so use this book as an excuse to learn
Git!
Finally, this book is not a complete and exhaustive reference on the Flask framework.
Most features are covered, but you should complement this book with the official Flask
documentation.
xii | Preface
• Chapter 6 introduces email support.
• Chapter 7 presents an application structure that is appropriate for medium and
large applications.
Part II, Example: A Social Blogging Application, builds Flasky, the open source blogging
and social networking application that I developed for this book:
Part III, The Last Mile, describes some important tasks not directly related to application
coding that need to be considered before publishing an application:
Preface | xiii
The git clone command installs the source code from GitHub into a flasky folder that
is created in the current directory. This folder does not contain just source code; a copy
of the Git repository with the entire history of changes made to the application is also
included.
In the first chapter you will be asked to check out the initial release of the application,
and then, at the proper places you will be instructed to move forward in the history.
The Git command that lets you move through the change history is git checkout. Here
is an example:
$ git checkout 1a
The 1a referenced in the command is a tag, a named point in the history of the project.
This repository is tagged according to the chapters of the book, so the 1a tag used in
the example sets the application files to the initial version used in Chapter 1. Most
chapters have more than one tag associated with them, so, for example, tags 5a, 5b, and
so on are incremental versions presented in Chapter 5.
In addition to checking out the source files for a version of the application, you may
need to perform some setup. For example, in some cases you will need to install addi‐
tional Python packages or apply updates to the database. You will be told when these
are necessary.
You will normally not modify the source files of the application, but if you do, then Git
will not let you check out a different revision, as that would cause your local changes to
be lost. Before you can check out a different revision, you will need to revert the files to
their original state. The easiest way to do this is with the git reset command:
$ git reset --hard
This command will destroy your local changes, so you should save anything you don’t
want to lose before you use this command.
From time to time, you may want to refresh your local repository from the one on
GitHub, where bug fixes and improvements may have been applied. The commands
that achieve this are:
$ git fetch --all
$ git fetch --tags
$ git reset --hard origin/master
The git fetch commands are used to update the commit history and the tags in your
local repository from the remote one on GitHub, but none of this affects the actual
source files, which are updated with the git reset command that follows. Once again,
be aware that any time git reset is used you will lose any local changes you have made.
Another useful operation is to view all the differences between two versions of the
application. This can be very useful to understand a change in detail. From the command
xiv | Preface
line, the git diff command can do this. For example, to see the difference between
revisions 2a and 2b, use:
$ git diff 2a 2b
The differences are shown as a patch, which is not a very intuitive format to review
changes if you are not used to working with patch files. You may find that the graphical
comparisons shown by GitHub are much easier to read. For example, the differences
between revisions 2a and 2b can be viewed on GitHub at https://github.com/miguelgrin
berg/flasky/compare/2a...2b
Preface | xv
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
xvi | Preface
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://www.bit.ly/flask-web-dev.
To comment or ask technical questions about this book, send email to bookques
[email protected].
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
I could not have written this book alone. I have received a lot of help from family, co-
workers, old friends, and new friends I’ve made along the way.
I’d like to thank Brendan Kohler for his detailed technical review and for his help in
giving shape to the chapter on Application Programming Interfaces. I’m also in debt to
David Baumgold, Todd Brunhoff, Cecil Rock, and Matthew Hugues, who reviewed the
manuscript at different stages of completion and gave me very useful advice regarding
what to cover and how to organize the material.
Writing the code examples for this book was a considerable effort. I appreciate the help
of Daniel Hofmann, who did a thorough code review of the application and pointed out
several improvements. I’m also thankful to my teenage son, Dylan Grinberg, who sus‐
pended his Minecraft addiction for a few weekends and helped me test the code under
several platforms.
O’Reilly has a wonderful program called Early Release that allows impatient readers to
have access to books while they are being written. Some of my Early Release readers
went the extra mile and engaged in useful conversations regarding their experience
working through the book, leading to significant improvements. I’d like to acknowledge
Preface | xvii
Sundeep Gupta, Dan Caron, Brian Wisti and Cody Scott in particular for the contri‐
butions they’ve made to this book.
The staff at O’Reilly Media has always been there for me. Above all I’d like to recognize
my wonderful editor, Meghan Blanchette, for her support, advice, and assistance from
the very first day we met. Meg has made the experience of writing my first book a
memorable one.
To conclude, I would like to give a big thank you to the awesome Flask community.
xviii | Preface
Discovering Diverse Content Through
Random Scribd Documents
ST. CROIX and MISACODA or BURNTWOOD RIVERS.
INTRODUCTORY MEMORANDA.
CHAPTER I.
Interval of the banks of the Mississippi, between the mouths of the River De Corbeau
and St. Croix, adverted to.—Plains above St. Anthony’s Falls, agricultural.—Fact
respecting the recession of the bison.—Geological change in the character of the
Mississippi, in crossing 45 deg. parallel.—Fort Snelling.—Council.—Reach the mouth of
the St. Croix.—Picturesque character of St. Croix Lake.—Traits of its natural history.—
Encamp near a diminutive kind of barrows.—“Standing Cedars.”—An Indian trader.—
Green-stone rock.—Falls of the St. Croix.—Traditionary account of an ancient Indian
battle, fought at these falls by the Chippewas, Saucs, Foxes, and Sioux.—Wahb Ojeeg.
On entering lake St. Croix we were favored with a fair wind, and
made use of our sails in passing it. As we approached its head, we
found the swell formidable, but were able, nevertheless, to keep the
lake. We debarked, on a marshy margin at its head, being the
commencement of the portage to the Brulé. As the river St. Croix
has its origin here, a few general remarks on its geographical
features, may be subjoined.—This stream is an important tributary to
the Upper Mississippi, originating on elevated grounds, and
consequently, having a rapid mean descent. Although not
remarkable for its length, its waters spread in a lateral line, an
unusual distance. It has many tributaries, connecting it, on the
north, with Rum river, on the south, with Chippewa river, and
towards the east with the Mauvais and the Brulé rivers of Lake
Superior. The main channel may be estimated, by its windings, at
two hundred miles. The length of its Namakagon fork, is estimated
to be one hundred and seventy miles, while that of its northern
branch does not probably exceed sixty-five miles. Both branches,
together with its lower tributaries, and their numerous lakes, yield
the northern rice plant. The abundance of the plant, has led to the
local term of the Folle Avoine country, a name by which it is
particularly known in the transactions of the Fur Trade.
It has a comparatively mild climate, and rich soil, and in addition
to the small fur bearing animals, on the sale of which the Indians
rely for their woollens, arms, and ammunition; it affords the
spontaneous means of subsistence, more fully, perhaps, than most
other parts of the northwest regions. Its present aggregate
population has been estimated the present year, at eight hundred
and ninety-five, say nine hundred souls, numbering those only who
are permanently located in its valley.—What quantity of furs and
peltries is annually got from it, and what amount of Indian goods are
required to pay for them, are questions which might be ascertained,
with general accuracy, by consulting official records. But it is
sufficient for the purposes of moral enquiry, to remark, that both the
supplies and the returns, are less than they were in former years,
and that there is a declension in the trade, which must at length
produce a migration of the Indians, or induce them to become
agriculturists. The fate that has overtaken other tribes, enjoying a
more southerly position, must inevitably overtake these bands. And
the period will probably arrive earlier, than it might be anticipated.
They occupy a portion of the Mississippi valley, which is adapted for
agriculture. Many parts of it, possess a rich soil, and are well
timbered. Other portions are prairie land, suited for pasturage. Its
most arid tracts abound in pine, and there is hardly a stream, of its
many tributaries which does not afford numerous eligible seats for
saw and grist mills. Hunting seems the only occupation, which
cannot be a permanent one. But,
In ancient times when the Indians were better than they now
are, when their laws were enforced by the chiefs, and when
every crime was promptly punished, there lived a noted hunter
and a just man, at a remote point on the north shore of Lake
Superior. He had a wife and two sons, who were usually left in
the lodge, while he went out in quest of the animals upon
whose flesh they subsisted. As game was then abundant, his
exertions were well rewarded, and he lived in the enjoyment of
every blessing. But there was at this time a venom preparing for
his heart, which was not the less poisonous, because it was for
a time kept in secret. His two little sons had observed the visits
of a neighboring hunter, during the absence of their father, and
they ventured to remonstrate with their mother on the propriety
of receiving clandestine visits, but she was in no temper to be
reasoned with. She rebuked them sharply, and finally, on their
intimation of disclosing the secret, threatened to kill them if
they made any disclosure They were frightened into silence. But
observing the continuance of an improper intercourse, kept up
by stealth as it were, they resolved at last to disclose the whole
matter to their father. The result was such as might be
anticipated. The father being satisfied with the infidelity of his
wife, took up a war club at a moment when he was not
perceived, and with a single blow despatched the object of his
jealousy. He then buried her under the ashes of his fire, took
down his lodge, and removed to a distant position.
But the spirit of the woman haunted the children who were
now grown up to the estate of young men. She appeared to
them in the shadows of evening. She terrified them in dreams.
She harassed their imaginations wherever they went, so that
their life was a life of perpetual terrors. They resolved to leave
the country, and commenced a journey of many days towards
the south. They at length came to the Poiwateeg falls. (St.
Mary’s.) But they had no sooner come in sight of these falls,
than they beheld the skull of the woman (their mother) rolling
along the beach after them. They were in the utmost fear, and
knew not what to do, to elude her, when one of them observed
a large crane sitting on a rock in the rapids. They called out to
the bird. “See, Grandfather, we are persecuted by a spirit. Come
and take us across the falls so that we may escape her.”
This crane was a bird of extraordinary size and great age. And
when first descried by the two sons, sat in a state of stupor, in
the midst of the most violent eddies of the foaming water. When
he heard himself addressed, he stretched forth his neck, with
great deliberation, and then raising himself on his wings flew
across to their assistance. “Be careful” said the crane, “that you
do not touch the back part of my head. It is sore, and should
you press against it, I shall not be able to avoid throwing you
both into the rapids.” They were, however, attentive on this
point, and were both safely landed on the south side of the
river. The crane then resumed its former position in the rapids.
But the skull now cried out. “Come Grandfather and carry me
over, for I have lost my children, and am sorely distressed.” The
aged bird flew to her assistance, but carefully repeated his
injunction, that she must by no means touch the back part of
his head, which had been hurt, and was not yet healed. She
promised to obey, but she soon felt a curiosity to know, where
the head of her carrier had been hurt, and how so aged a bird
could have acquired such a bad wound. She thought it strange,
and before they were half way over the rapids, could not resist
the inclination she felt to touch the affected part. Instantly the
crane threw her into the rapids. The skull floated down from
rock to rock, striking violently against their hard edges, until it
was battered to fragments, and the sons were thus happily and
effectually relieved from their tormentor. But the brains of the
woman, when the skull was dashed against the rocks, fell into
the water, in the form of small white roes, which soon assumed
the shape of a novel kind of fish, possessing a whiteness of
color peculiar to itself; and these rapids have ever since been
well stocked with this new and delicious species of fish.
The sons meantime took up their permanent abode at these
Falls, becoming the progenitors of the present tribe, and in
gratitude to their deliverer adopted the Crane[25] as their
Totem.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
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.
ebookfinal.com