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
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781784398194
Vendor :
Google
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
€18.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
€189.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
€264.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 99.97
Python for Google App Engine
€24.99
Mastering Google App Engine
€36.99
Mastering Object-oriented Python
€37.99
Total 99.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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.