Book Image

Mastering Flask

By : Jack Stouffer
Book Image

Mastering Flask

By: Jack Stouffer

Overview of this book

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.
Table of Contents (20 chapters)
Mastering Flask
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

CRUD


In every storage mechanism for data, there are four basic types of functions: Create, Read, Update, and Delete (CRUD). These allow all the basic ways of manipulating and viewing data needed for our web apps. To use these functions, we will use an object on the database named the session. Sessions will be explained later in the chapter, but for now, think of them as a storage location for all of our changes to the database.

Creating models

To create a new row in your database using our models, add the model to the session and commit objects. Adding an object to the session marks its changes for saving, and committing is when the session is saved to the database as follows:

>>> user = User(username='fake_name')
>>> db.session.add(user)
>>> db.session.commit()

It is simple to add a new row to our table.

Reading models

After we have added data to our database, data can be queried using Model.query. For those who use SQLAlchemy, this is shorthand for db.session.query...