Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python for Google App Engine
Python for Google App Engine

Python for Google App Engine: Master the full range of development features provided by Google App Engine to build and run scalable web applications in Python

eBook
NZ$26.99 NZ$38.99
Paperback
NZ$48.99
Subscription
Free Trial
Renews at $19.99p/m

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

Python for Google App Engine

Chapter 2. A More Complex Application

Web applications commonly provide a set of features such as user authentication and data storage. As we know from the previous chapter, App Engine provides the services and tools needed to implement such features and the best way to learn how to use them is by writing a web application and seeing the platform in action.

In this chapter, we will cover the following topics:

  • Further details of the webapp2 framework
  • How to authenticate users
  • Storing data on Google Cloud Datastore
  • Building HTML pages using templates
  • Serving static files

Experimenting on the Notes application

To better explore App Engine and Cloud Platform capabilities, we need a real-world application to experiment on; something that's not trivial to write, with a reasonable list of requirements so that it can fit in this book. A good candidate is a note-taking application; we will name it Notes.

Notes enable the users to add, remove, and modify a list of notes; a note has a title and a body of text. Users can only see their personal notes, so they must authenticate before using the application.

The main page of the application will show the list of notes for logged-in users and a form to add new ones.

The code from the helloworld example in the previous chapter is a good starting point. We can simply change the name of the root folder and the application field in the app.yaml file to match the new name we chose for the application, or we can start a new project from scratch named notes.

Authenticating users

The first requirement for our Notes application is showing the home page only to users who are logged in and redirect others to the login form; the users service provided by App Engine is exactly what we need and adding it to our MainHandler class is quite simple:

import webapp2

from google.appengine.api import users

class MainHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user is not None:
            self.response.write('Hello Notes!')
        else:
        login_url = users.create_login_url(self.request.uri)
        self.redirect(login_url)
app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

The user package we import on the second line of the previous code provides access to users' service functionalities. Inside the get() method of the MainHandler class, we first check whether the user visiting the page has logged in or not. If they have, the get_current_user() method...

HTML templates with Jinja2

Web applications provide rich and complex HTML user interfaces, and Notes is no exception but, so far, response objects in our applications contained just small pieces of text. We could include HTML tags as strings in our Python modules and write them in the response body but we can imagine how easily it could become messy and hard to maintain the code. We need to completely separate the Python code from HTML pages and that's exactly what a template engine does. A template is a piece of HTML code living in its own file and possibly containing additional, special tags; with the help of a template engine, from the Python script, we can load this file, properly parse special tags, if any, and return valid HTML code in the response body. App Engine includes in the Python runtime a well-known template engine: the Jinja2 library.

To make the Jinja2 library available to our application, we need to add this code to the app.yaml file under the libraries section:

libraries...

Handling forms

The main page of the application is supposed to list all the notes that belong to the current user but there isn't any way to create such notes at the moment. We need to display a web form on the main page so that users can submit details and create a note.

To display a form to collect data and create notes, we put the following HTML code right below the username and the logout link in the main.html template file:

{% if note_title %}
<p>Title: {{note_title}}</p>
<p>Content: {{note_content}}</p>
{% endif %}

<h4>Add a new note</h4>
<form action="" method="post">
  <div class="form-group">
    <label for="title">Title:</label>
    <input type="text" id="title" name="title" />
  </div>
  <div class="form-group">
      <label for="content">Content:</label>
      <textarea id="content&quot...

Persisting data in Datastore

Even if users can log in and submit a note, our application isn't very useful until notes are stored somewhere. Google Cloud Datastore is the perfect place to store our notes. As part of App Engine's infrastructure, it takes care of data distribution and replication, so all we have to do is define store and retrieve our entities using the Python NDB (Next DB) Datastore API.

Note

There are currently two APIs available in the Python runtime to interact with Datastore: the DB Datastore API, also known as ext.db, and the NDB Datastore API. Even if both the APIs store exactly the same data in Datastore, in this book, we will only use NDB; it is more recent, provides more features, and its API is slightly more robust.

An entity has one or more properties that in turn have a name and a type; each entity has a unique key that identifies it, and instead of storing different data in different tables as in a relational database, every entity in Datastore is categorized...

Using static files

Usually web applications make use of CSS and JavaScript resources to provide a better user experience. For efficiency reasons, such content is not dynamically served by the WSGI application and are delivered by App Engine as static files instead.

We know from the previous chapter that App Engine provides two types of handlers, script handlers and static file handlers. We add a static file handler to our app.yaml configuration file like this:

handlers:
- url: /static
  static_dir: static

- url: .*
  script: main.app

The syntax is almost the same as for script handlers. We specify a URL to map as a regular expression but instead of providing a Python script to handle requests, we specify a filesystem path relative to the application root where the files and directories that need to be served as static resources are located.

Note

We are now going to provide a minimal style for our HTML pages by manually coding some CSS rules. While it is acceptable for the scope of the book...

Summary

Thanks to App Engine, we have already implemented a rich set of features with a relatively small effort so far.

In this chapter, we have discovered some more details about the webapp2 framework and its capabilities, implementing a nontrivial request handler. We have learned how to use the App Engine users service to provide users authentication. We have delved into some fundamental details of Datastore and now we know how to structure data in grouped entities and how to effectively retrieve data with ancestor queries. In addition, we have created an HTML user interface with the help of the Jinja2 template library, learning how to serve static content such as CSS files.

In the next chapter, we will keep on adding more and more features to the Notes application, learning how to store uploaded files on Google Cloud Storage, manipulate images, and deal with long operations and scheduled tasks. We will also make the application capable of sending and receiving e-mails.

Left arrow icon Right arrow icon
Download code icon Download Code

Description

If you are a Python developer, whether you have experience in web applications development or not, and want to rapidly deploy a scalable backend service or a modern web application on Google App Engine, then this book is for you.

Who is this book for?

If you are a Python developer, whether you have experience in web applications development or not, and want to rapidly deploy a scalable backend service or a modern web application on Google App Engine, then this book is for you.

What you will learn

  • Persist and manage data in the cloud datastore with the NDB Python API
  • Run asynchronous tasks with task queue and Cron
  • Set up, use, and manage a MySQL server instance on Cloud SQL
  • Employ channels to develop realtime applications with push notifications from the server
  • Write a complete Django application using Cloud SQL as the data backend
  • Use cloud endpoints to rapidly provide REST APIs for your mobile clients

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 27, 2015
Length: 198 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392376
Vendor :
Google
Languages :

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 : Jan 27, 2015
Length: 198 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392376
Vendor :
Google
Languages :

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 NZ$7 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 NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 192.97
Python for Google App Engine
NZ$48.99
Mastering Google App Engine
NZ$71.99
Mastering Object-oriented Python
NZ$71.99
Total NZ$ 192.97 Stars icon

Table of Contents

9 Chapters
1. Getting Started Chevron down icon Chevron up icon
2. A More Complex Application Chevron down icon Chevron up icon
3. Storing and Processing Users' Data Chevron down icon Chevron up icon
4. Improving Application Performance Chevron down icon Chevron up icon
5. Storing Data in Google Cloud SQL Chevron down icon Chevron up icon
6. Using Channels to Implement a Real-time Application Chevron down icon Chevron up icon
7. Building an Application with Django Chevron down icon Chevron up icon
8. Exposing a REST API with Google Cloud Endpoints Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(10 Ratings)
5 star 40%
4 star 40%
3 star 10%
2 star 10%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




jak_jak May 02, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is an excellent bargain that was well worth the money spent and recommended to anyone interested.
Amazon Verified review Amazon
Loris Apr 25, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is an excellent guide to get you started with Google App Engine with Python. As the author mentions in the book, a medium-high knowledge of Python is required to follow the book. However the reader is not required to have any prior knowledge of Google App Engine. I have been using Python for a long time and this book was an excellent starting point to use Google App Engine. Also, a basic understanding of web apps is recommended.The first chapter helps the reader to get started with Google App Engine. It provides instructions on how to set up the runtime for Linux, OS X and Windows. In the following chapters the author implements a note-taking web application increasing chapter after chapter the features of the app and the complexity of the code, This lets the reader to gradually assimilate the new concepts showed in each chapters and to smoothly progress in the book. The firsts examples use the webapp2 framework while the last chapters use the much more popular Django framework.The book is well written, covers all the basic features of Google App Engine, and provides a lot of reusable code.
Amazon Verified review Amazon
SuJo May 11, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Python for Google App EnginePublisher Link: https://www.packtpub.com/virtualization-and-cloud/python-google-app-engine5/5 - Know Python prior to engaging in this book, no need for the Google App Engine experience though.The book as others mention creates a basic web application, then you learn more and go back over the content to create a more robust expandable application that uses the previous example. The book uses Google SQL Cloud, however I opted to just keep it on my local machine. Still worth checking it out though despite me not wanting Google to have any more of my data. As for the book itself, it's structured, logical, stays on track, and has a lot of up sides. My favorite part would be utilizing memcache and tracking connections, start seeing some strange stuff well you can now act on it or let customers know that you're experiencing issues and are working to resolve it. I'm also a very huge fan of the MVC pattern, so using modular design was also something that made me fall in love with this book even more. All in all I would highly recommend this book and can't wait to build up on top of what I've already learned.
Amazon Verified review Amazon
ruben May 09, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Python for Google App Engine is a very understandable title, because of its explanation, this title is very useful for people who want to learn about how to use the WEB technologies, develop web sites with the newest technologies and the frameworks.The book has the basics to start learning how use the Google API to develop web sites with this toolsI really recommend the book because it helps me to learn about the Web Services like RESP API, I could understand the main idea of how the google framework Works.Applications are the main topic of this title, very interesting explanations, very useful for projects.Thanks
Amazon Verified review Amazon
Tim Crothers May 10, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Overall this book provides good coverage of writing an app for Google App Engine using Python. The main shortfall of the book is that it is very terse on explanations and only has a single example which is built up over the chapters. The included code and example is very good so if you learn by examining other people's code with some additional explanation then this book is for you. The approach used by the author also means you have some solid python code to start your own efforts from. More explanations of alternatives and additional approaches would be helpful but all-in-all a very good value for those looking to use Python to build applications on Google App Engine.
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.