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
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
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

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 : 9781784398194
Vendor :
Google
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Jan 27, 2015
Length: 198 pages
Edition : 1st
Language : English
ISBN-13 : 9781784398194
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 130.97
Python for Google App Engine
$32.99
Mastering Google App Engine
$48.99
Mastering Object-oriented Python
$48.99
Total $ 130.97 Stars icon
Banner background image

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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela