Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Flask Framework
Learning Flask Framework

Learning Flask Framework: Build dynamic, data-driven websites and modern web applications with Flask

eBook
₱579.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning Flask Framework

Chapter 2. Relational Databases with SQLAlchemy

Relational databases are the bedrock upon which almost every modern Web application is built. Learning to think about your application in terms of tables and relationships is one of the keys to a clean, well-designed project. As you will see in this chapter, the data model you choose early on will affect almost every facet of the code that follows. We will be using SQLAlchemy, a powerful object relational mapper that allows us to abstract away the complexities of multiple database engines, to work with the database directly from within Python.

In this chapter, we shall:

  • Present a brief overview of the benefits of using a relational database
  • Introduce SQLAlchemy, the Python SQL Toolkit and Object Relational Mapper
  • Configure our Flask application to use SQLAlchemy
  • Write a model class to represent blog entries
  • Learn how to save and retrieve blog entries from the database
  • Perform queries – sorting, filtering, and aggregation
  • Build a tagging...

Why use a relational database?

Our application's database is much more than a simple record of things that we need to save for future retrieval. If all we needed to do was save and retrieve data, we could easily use flat text files. The fact is, though, that we want to be able to perform interesting queries on our data. What's more, we want to do this efficiently and without reinventing the wheel. While non-relational databases (sometimes known as NoSQL databases) are very popular and have their place in the world of the web, relational databases long ago solved the common problems of filtering, sorting, aggregating, and joining tabular data. Relational databases allow us to define sets of data in a structured way that maintains the consistency of our data. Using relational databases also gives us, the developers, the freedom to focus on the parts of our app that matter.

In addition to efficiently performing ad hoc queries, a relational database server will also do the following...

Introducing SQLAlchemy

SQLAlchemy is an extremely powerful library for working with relational databases in Python. Instead of writing SQL queries by hand, we can use normal Python objects to represent database tables and execute queries. There are a number of benefits to this approach, as follows:

  • Your application can be developed entirely in Python.
  • Subtle differences between database engines are abstracted away. This allows you to do things just like a lightweight database, for instance, use SQLite for local development and testing, then switch to the databases designed for high loads (such as PostgreSQL) in production.
  • Database errors are less common because there are now two layers between your application and the database server: the Python interpreter itself (this will catch the obvious syntax errors), and SQLAlchemy, which has well-defined APIs and its own layer of error-checking.
  • Your database code may become more efficient, thanks to SQLAlchemy's unit-of-work model that helps...

Creating the Entry model

A model is the data representation of a table of data that we want to store in the database. These models have attributes called columns that represent the data items in the data. So, if we were creating a Person model, we might have columns for storing the first and last name, date of birth, home address, hair color, and so on. Since we are interested in creating a model to represent blog entries, we will have columns for things like the title and body content.

Note

Note that we don't say a People model or Entries model – models are singular even though they commonly represent many different objects.

With SQLAlchemy, creating a model is as easy as defining a class and specifying a number of attributes assigned to that class. Let's start with a very basic model for our blog entries. Create a new file named models.py in the blog project's app/ directory and enter the following code:

import datetime, re
from app import db

def slugify(s):
    return...

Retrieving blog entries

While creating, updating, and deleting are fairly straightforward operations, the real fun starts when we look at ways to retrieve our entries. We'll start with the basics, and then work our way up to more interesting queries.

We will use a special attribute on our model class to make queries: Entry.query. This attribute exposes a variety of APIs for working with the collection of entries in the database.

Let's simply retrieve a list of all the entries in the Entry table:

In []: entries = Entry.query.all()
In []: entries  # What are our entries?
Out[]: [<Entry u'First entry'>, <Entry u'Second entry'>, <Entry u'Third entry'>, <Entry u'Fourth entry'>]

As you can see, in this example the query returns a list of Entry instances that we created. When no explicit ordering is specified, the entries are returned to us in an arbitrary order chosen by the database. Let's specify that we want the entries...

Building a tagging system

Tags are a lightweight taxonomy system that is perfect for blogs. Tags allow you to apply multiple categories to a blog post and allow multiple posts to be related to one another outside their category. On my own blog I use tags to organize the posts, so that people interested in reading my posts about Flask need only look under the "Flask" tag and find all the relevant posts. As per the spec that we discussed in Chapter 1, Creating Your First Flask Application, each blog entry can have as few or as many tags as you want, so a post about Flask might be tagged with both Flask and Python. Similarly, each tag (for example, Python) can have multiple entries associated with it. In database parlance, this is called a many-to-many relationship.

In order to model this, we must first create a model to store tags. This model will store the names of tags we use, so after we've added a few tags the table might look something like the following one:

id

tag

1...

Why use a relational database?


Our application's database is much more than a simple record of things that we need to save for future retrieval. If all we needed to do was save and retrieve data, we could easily use flat text files. The fact is, though, that we want to be able to perform interesting queries on our data. What's more, we want to do this efficiently and without reinventing the wheel. While non-relational databases (sometimes known as NoSQL databases) are very popular and have their place in the world of the web, relational databases long ago solved the common problems of filtering, sorting, aggregating, and joining tabular data. Relational databases allow us to define sets of data in a structured way that maintains the consistency of our data. Using relational databases also gives us, the developers, the freedom to focus on the parts of our app that matter.

In addition to efficiently performing ad hoc queries, a relational database server will also do the following:

  • Ensure that...

Introducing SQLAlchemy


SQLAlchemy is an extremely powerful library for working with relational databases in Python. Instead of writing SQL queries by hand, we can use normal Python objects to represent database tables and execute queries. There are a number of benefits to this approach, as follows:

  • Your application can be developed entirely in Python.

  • Subtle differences between database engines are abstracted away. This allows you to do things just like a lightweight database, for instance, use SQLite for local development and testing, then switch to the databases designed for high loads (such as PostgreSQL) in production.

  • Database errors are less common because there are now two layers between your application and the database server: the Python interpreter itself (this will catch the obvious syntax errors), and SQLAlchemy, which has well-defined APIs and its own layer of error-checking.

  • Your database code may become more efficient, thanks to SQLAlchemy's unit-of-work model that helps reduce...

Left arrow icon Right arrow icon

Description

Flask is a small and powerful web development framework for Python. It does not presume or force a developer to use a particular tool or library. Flask supports extensions that can add application features as if they were implemented in Flask itself. Flask’s main task is to build web applications quickly and with less code. With its lightweight and efficient web development framework, Flask combines rapid development and clean, simple design. This book will take you through the basics of learning how to apply your knowledge of Python to the web. Starting with the creation of a “Hello world” Flask app, you will be introduced to the most common Flask APIs and Flask’s interactive debugger. You will learn how to store and retrieve blog posts from a relational database using an ORM and also to map URLs to views. Furthermore, you will walk through template blocks, inheritance, file uploads, and static assets. You will learn to authenticate users, build log in/log out functionality, and add an administrative dashboard for the blog. Moving on, you will discover how to make Ajax requests from the template and see how the Mock library can simplify testing complex interactions. Finally, you will learn to deploy Flask applications securely and in an automated, repeatable manner, and explore some of the most popular Flask resources on the web.

Who is this book for?

This book is for anyone who wants to develop their knowledge of Python into something that can be used on the web. Flask follows the Python design principles and can be easily understood by anyone who knows Python, and even by those who do not.

What you will learn

  • Create your web pages to add modularity and flexibility to your web app using templates
  • Store and retrieve relational data using SQLAlchemy
  • Develop schema migrations with Alembic
  • Produce an admin section using flaskadmin
  • Build RESTful APIs using FlaskRestless
  • Simulate requests and sessions using the Flask test client
  • Make Ajax requests from Jinja2 templates

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 26, 2015
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781783983377
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 26, 2015
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781783983377
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 7,502.97
Learning Flask Framework
₱2500.99
Flask Blueprints
₱2500.99
Mastering Flask
₱2500.99
Total 7,502.97 Stars icon
Banner background image

Table of Contents

11 Chapters
1. Creating Your First Flask Application Chevron down icon Chevron up icon
2. Relational Databases with SQLAlchemy Chevron down icon Chevron up icon
3. Templates and Views Chevron down icon Chevron up icon
4. Forms and Validation Chevron down icon Chevron up icon
5. Authenticating Users Chevron down icon Chevron up icon
6. Building an Administrative Dashboard Chevron down icon Chevron up icon
7. AJAX and RESTful APIs Chevron down icon Chevron up icon
8. Testing Flask Apps Chevron down icon Chevron up icon
9. Excellent Extensions Chevron down icon Chevron up icon
10. Deploying Your Application Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(2 Ratings)
5 star 50%
4 star 50%
3 star 0%
2 star 0%
1 star 0%
James Anderson Jun 01, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A good book to learn from, but needs to updated to the latest Flask software.
Amazon Verified review Amazon
Zweibier Jul 09, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I read few books on Flask, and this is one is quite good.The book walks through, step by step, building of a moderately complex Flask application, a blog engine.Many important aspects are discussed in detail, including model persistence with SQLAlchemy, login subsystem with Flask-login, building REST API with Flask-Restless and so on.By working through this book, I have learned how to design, structure, and build a real-world Flask application with all bells and whistles.Why not 5 stars then?Editing is quite subpar, there are many mistakes which should've be easily uncovered by a diligent editor, there is no errata (at least I didn't find it), no github repository with chapter by chapter source code; all I was able to find, was a source code of the completed application, on the publisher's Web site,
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.