SlideShare a Scribd company logo
1 of 60
Building webapps for the Cloud
with Python and Google App Engine

              Juan Gomez
          PythonKC Co-founder
            October 29th, 2011
Agenda
1. Intro to Google App Engine (GAE for short)
   •   Brief intro to Python
   •   Structure of a Python webapp
   •   Setting up your dev environment with GAE
   •   App Engine Architecture
   •   The App Engine datastore and GQL
2. Brief intro to Django
   • Using templates with GAE
3. Quick demo of a sample webapp
4. Beyond the basics
   • Scalability & Security
   • Quotas
   • Using the Google Data Services API
5. Summary
   • Where to go from here?
   • References                                   2
Why Google App Engine?
Challenges building web apps




                               3
Run your web applications
on Google’s infrastructure
Easy to start.
Easy to scale.
The Components
1. Scalable Serving Infrastructure

       2. Python Runtime

  3. Software Development Kit

  4. Web based Admin Console

          5. Datastore




                                     7
4. Web-based Admin Console




                             8
Click to Deploy




                  9
Memcache

          Send E-Mail

      Make HTTP Requests

Authenticate with Google Accounts

       Image Manipulation
Does one thing well:
 running web apps
12
13
A Python Code Sample

 x = 34 - 23            # A comment.
 y = “Hello”            # Another one.
 z = 3.45
 if z is not 3.46 or y is “Hello”:
     x = x + 1
     y = y + “ World”   # String concat.
 print x
 print y




                                      14
Enough to Understand the Code

• First assignment to a variable creates it
• Assignment is = and comparison is == (or is)
• For numbers + - * / % are as expected
 • Special use:
      • + for string concatenation
      • % for string formatting (as in C’s printf)
• Logical operators are words (and, or,
  not) not symbols (&&, ||, !).
• The basic printing command is print


                                                     15
Comments
• Start comments with #, rest of line is ignored
• Can include a “documentation string” as the
  first line of a new function or class you define
• Development environments, debugger, and
  other tools use it: it’s good style to include one
   def my_function(x, y):
     “““This is the docstring. This
     function does blah blah blah.”””
     # The code would go here...




                                                16
Python and Types

• Everything is an object!

• “Dynamic Typing”->    Data types determined automatically.

• “Strong Typing” ->    Enforces them after it figures them out.


x = “the answer is ”   # Decides x is string.
y = 23                # Decides y is integer.
print x + y   # Python will complain about this.




                                                      17
Basic Datatypes

• Integers (default for numbers)
      •z = 5 / 2 # Answer 2, integer division
• Floats
      •x = 3.456
• Strings
  • Can use “” or ‘’ to specify with “abc” == ‘abc’
  • Unmatched can occur within the string: “matt’s”
  • Use triple double-quotes for multi-line strings or strings
    that contain both ‘ and “ inside of them:
    “““a‘b“c”””



                                                         18
Whitespace

Whitespace is meaningful in Python: especially
indentation and placement of newlines
•Use a newline to end a line of code
  Use  when must go to next line prematurely

•No braces {} to mark blocks of code, use
consistent indentation instead
  • First line with less indentation is outside of the block
  • First line with more indentation starts a nested block

•Colons start of a new block in many constructs,
e.g. function definitions, then clauses


                                                               19
Assignment
• You can assign to multiple names at the
  same time
  >>> x, y = 2, 3
  >>> x
  2
  >>> y
  3
This makes it easy to swap values
  >>> x, y = y, x
• Assignments can be chained
  >>> a = b = x = 2
                                      20
A Python Code Sample
x = 34 - 23            # A comment.
y = “Hello”            # Another one.
z = 3.45
if z is not 3.46 or y is “Hello”:
    x = x + 1
    y = y + “ World”   # String concat.
print x
print y




                                     21
Side by Side with Java
                      Java (C#)                                             Python
public class Employee                                        class Employee():
{
    private String myEmployeeName;
    private int    myTaxDeductions = 1;
    private String myMaritalStatus = "single";
                                                              def __init__(self,
                                                                     employeeName
    public Employee(String EmployeName)
    {                                                                , taxDeductions=1
        this(EmployeName, 1);
    }                                                                , maritalStatus="single"

                                                                     ):
    public Employee(String EmployeName, int taxDeductions)
    {
       this(EmployeName, taxDeductions, "single");
    }                                                         self.employeeName     = employeeName
    public Employee(String EmployeName,
           int taxDeductions,                                  self.taxDeductions   = taxDeductions
           String maritalStatus)
                                                               self.maritalStatus   = maritalStatus
    {
       this.myEmployeeName    = EmployeName;
       this.myTaxDeductions   = taxDeductions;
       this.myMaritalStatus   = maritalStatus;
    }
}


                                                                                         22
Life is Short
 (You Need Python)
               - Bruce Eckel (Thinking in C++)




                                  23
Things to read through:

                    The Quick Python Book, 2nd Ed
                    http://amzn.to/lXKzH5


                    “Learn Python The Hard Way”
                    http://learnpythonthehardway.org




Python 101 – Beginning Python
http://www.rexx.com/~dkuhlman/python_101/python_101.html

                                                  24
Things to refer to:

                      The Python Standard Library
                      by Example
                      http://amzn.to/sx3It1
                      Programming Python, 4th Ed
                      http://amzn.to/kWjaW2


The Official Python Tutorial
http://www.python.org/doc/current/tut/tut.html
The Python Quick Reference
http://rgruet.free.fr/PQR2.3.html            25
26
Google App Engine
App Engine Does One Thing Well


• App Engine handles HTTP(S) requests, nothing else
  – Think RPC: request in, processing, response out
  – Works well for the web and AJAX; also for other services
• App configuration is dead simple
  – No performance tuning needed
• Everything is built to scale
  – “infinite” number of apps, requests/sec, storage capacity
  – APIs are simple, stupid




                                                                28
And that allows it to:


•   Serve static files
•   Serve dynamic requests
•   Store data
•   Call web services
•   Authenticate against Google’s user database
•   Send e-mail, process images, use memcache




                                                  29
Scaling
•   5 million page views a month at the free quota
•   Low-usage apps: many apps per physical host
•   High-usage apps: multiple physical hosts per app
•   Stateless APIs are trivial to replicate
•   Memcache is trivial to shard
•   Datastore built on top of Bigtable; designed to scale well
    – Abstraction on top of Bigtable
    – API influenced by scalability
       • No joins
       • Recommendations: denormalize schema; precompute joins



                                                        30
Python webapps

• App Engine includes a simple web application
 framework called webapp.
• webapp is a WSGI-compatible framework.
• You can use webapp or any other WSGI
  framework with GAE (like web.py, CherryPy,
  Tornado, Django)
• Basic apps need Config file + webapp CGI




                                           31
Config file (No XML!)

• A webapp specifies runtime configuration, including
 versions and URLs, in a file named app.yaml.
application: myapp
version: 1
runtime: python
api_version: 1

handlers:
- url: /admin/.*
  script: admin.py
  login: admin

- url: /index.html
  script: home.py

- url: /(.*.(gif|png|jpg))
  static_files: static/1
  upload: static/(.*.(gif|png|jpg))
                                                    32
Structure of a Python webapp

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

application = webapp.WSGIApplication([('/', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

                                                     33
Setting up your dev environment with GAE

• The dev environment is really, really nice
• Download the (open source) SDK
  – http://code.google.com/appengine/downloads.html
  – Google_App_Engine_SDK_for_Python

• a full simulation of the App Engine environment
• dev_appserver.py myapp for a local
  webserver
• appcfg.py update myapp to deploy to the
  cloud
• You get a GUI on OS X and Windows.

                                                      34
App Engine Architecture
                    req/resp
 stateless APIs                R/O FS


    urlfech         Python     stdlib
                      VM
     mail
                    process     app
    images



   stateful                        datastore
    APIs      memcache


                                               35
The Datastore
• Based on “BigTable”
• Schemaless
• Scales infinitely
• NoSQL, with SQL type queries (GQL)
  – No joins (they do have “reference fields”)
  – No aggregate queries - not even count()!
  – Hierarchy affects sharding and transactions
  – All queries must run against an existing index
• Maybe the best part of App Engine!



                                                     36
Hierarchical Datastore
• Entities have a Kind, a Key, and Properties
  – Entity -> Record -> Python dict -> Python class instance
  – Key -> structured foreign key; includes Kind
  – Kind -> Table -> Python class
  – Property -> Column or Field; has a type
• Dynamically typed: Property types are recorded per Entity
• Key has either id or name
  – the id is auto-assigned; alternatively, the name is set by app
  – A key can be a path including the parent key, and so on
• Paths define entity groups which limit transactions
  – A transaction locks the root entity (parentless ancestor key)


                                                               37
Creating an Entity in the Datastore

from google.appengine.ext import db

...

class FoursquareUser(db.Model):
    """Creation of an entity of the kind 'FoursquareUser'"""
    created = db.DateTimeProperty(auto_now_add=True)
    name = db.TextProperty()
    email = db.TextProperty()
    description = db.StringProperty(multiline=True)




                                                     38
GQL
• GQL is a SQL-like language for retrieving entities or keys
    from the datastore.
• GQL's features are different from a query language for a
    traditional relational database.
• GQL syntax is (very) similar to that of SQL

•  SELECT [* | __key__] FROM <kind>
    [WHERE <condition> [AND <condition> ...]]
    [ORDER BY <property> [ASC | DESC] [, <property> [ASC |
DESC] ...]]
    [LIMIT [<offset>,]<count>]
    [OFFSET <offset>]

    <condition> := <property> {< | <= | > | >= | = | != } <value>
    <condition> := <property> IN <list>
    <condition> := ANCESTOR IS <entity or key>



                                                             39
Querying my FoursquareUser Entity

from google.appengine.ext import db
...
# I can query the datastore using the Query API
query = db.Query(FoursquareUser)
# Or the methods inherited form db.Model
model_query = FoursquareUser.all()
# Or using GQL
GQL_query = db.GqlQuery("SELECT * FROM FoursquareUser")

# I can print the results to the HTTP response object
for user in query:
    self.response.out.write("User name: %s" % user["name"])
    self.response.out.write("User email: %s" % user["email"])




                                                     40
Creating the Views
• HTML embedded in code is messy and
 difficult to maintain.


• It's better to use a templating system.
  – HTML is kept in a separate files with special syntax to indicate
    where the data from the application appears in the view.
• There are many templating systems for Python: EZT,
 Cheetah, ClearSilver, Quixote, and Django are just a
 few.
• You can use your template engine of choice by bundling
 it with your application code.
• Or you can use Django out of the box!

                                                               41
It’s a magical pony!
Why use Django over webapp?

• Django templating is one of the best in its
  class
• Django has easy cookies and custom 500
  errors
• Django is less verbose
• Django middleware is really handy
• URL patterns
  – mapping between URL patterns (RegEx) to callback
    functions (views).
  – URLconf

                                               43
Using templates with GAE


from django.conf.urls.defaults import *
from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello, World!")

urlpatterns = patterns('', ('^$', hello),)

# You have to write even less code!




                                           44
Quick demo of a sample webapp




                                45
Automatic Scaling to Application Needs
• You don’t need to configure your resource needs
• One CPU can handle many requests per second
• Apps are hashed (really mapped) onto CPUs:
  – One process per app, many apps per CPU
  – Creating a new process is a matter of cloning a generic “model”
    process and then loading the application code (in fact the
    clones are pre-created and sit in a queue)
  – The process hangs around to handle more requests (reuse)
  – Eventually old processes are killed (recycle)
• Busy apps (many QPS) get assigned to multiple CPUs
  – This automatically adapts to the need
     • as long as CPUs are available


                                                                 46
Security
• Prevent the bad guys from breaking (into) your app

• Constrain direct OS functionality
  –   no processes, threads, dynamic library loading (use Task Queue)
  –   no sockets (use urlfetch API)
  –   can’t write files (use datastore)
  –   disallow unsafe Python extensions (e.g. ctypes)


• Limit resource usage
  – Limit 10,000 files per app, adding up to 32 MB
  – Hard time limit of 60 seconds per request
  – Daily Max of 6.50 CPU hours (CPU cycles on 1.2 GHz Intel x86)
  – Hard limit of 32 MB on request and response size, API call size,
    etc.
  – Quota system for number of requests, API calls, emails sent, etc
                                                              47
Preserving Fairness Through Quotas
• Everything an app does is limited by quotas.
• If you run out of quota that particular operation is
 blocked
• Free quotas are tuned so that a well-written app (light
 CPU/datastore use) can survive a moderate
 “slashdotting”
• The point of quotas is to be able to support a very large
 number of small apps.
• Large apps need raised quotas ($$$)




                                                         48
Quotas   Costs




                 49
Quotas   Quota’s




                   50
Quotas




         51
Using the Google Data Service API

   import gdata.docs.service

# Create a client class which will make HTTP requests with
# Google Docs server.
client = gdata.docs.service.DocsService()
# Authenticate using your Google Docs email address and
# password.
client.ClientLogin('joe@gmail.com', 'password')

# Query the server for an Atom feed containing a list of your
# documents.
documents_feed = client.GetDocumentListFeed()
# Loop through the feed and extract each document entry.
for document_entry in documents_feed.entry:
  # Display the title of the document on the command line.
  print document_entry.title.text




                                                        52
What about vendor Lock-in?




                             53
What about vendor Lock-in?

• Use Django-nonrel
  – independent branch of Django that adds NoSQL
    database support to the ORM
    http://www.allbuttonspressed.com/projects/django-
    nonrel
  – No JOINs! :-(
• Port existing Django projects with very few
  changes!
• Switch from Bigtable to other NoSQL DBs
  – MongoDB, SimpleDB. (soon Cassandra, CouchDB)
• Move freely between Django hosting providers
  – ep.io, gondor.io, Heroku or your own VPS
                                                  54
Where to go from here?

• Learn Python!
• Download the App Engine SDK
• Build Apps...Many Apps
• Learn Django! (is awesome)
• Join a local Python User Group
 – http://www.pyowa.org or @pyowa on Twitter.
 – http://pythonkc.com/ or @pythonkc on Twitter.
                                                   55
Resources


• Read the Articles on the Google App Engine site.
  – http://code.google.com/appengine/docs/python/gettingstarted/
  – http://code.google.com/appengine/docs/python/overview.html
  – http://appengine-cookbook.appspot.com/
• Keep up with new releases through the Blog
  – http://googleappengine.blogspot.com/
• Read the source code from the SDK
   – http://code.google.com/p/googleappengine/
   – Maybe you will find an undocumented API.


                                                           56
Things to read through:

                 Programming Google App
                 Engine. (Python & Java)
                 http://amzn.to/ovzX4q




                                       57
Before the Q & A...




                      58
Yes!   Slides can be downloaded here:
http://www.slideshare.net/_juandg/gae_icc_fall2011

                                            59
Q&A
• Anything goes




                  60

More Related Content

What's hot

DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
Graham Dumpleton
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
Qiangning Hong
 

What's hot (20)

DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Python tour
Python tourPython tour
Python tour
 
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207
 
asyncio internals
asyncio internalsasyncio internals
asyncio internals
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To Golang
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 

Viewers also liked

Viewers also liked (13)

Google app-engine-with-python
Google app-engine-with-pythonGoogle app-engine-with-python
Google app-engine-with-python
 
Google app engine python
Google app engine   pythonGoogle app engine   python
Google app engine python
 
App Engine On Air: Munich
App Engine On Air: MunichApp Engine On Air: Munich
App Engine On Air: Munich
 
App Engine for Python Developers
App Engine for Python DevelopersApp Engine for Python Developers
App Engine for Python Developers
 
Introduccion app engine con python
Introduccion app engine con pythonIntroduccion app engine con python
Introduccion app engine con python
 
App Engine
App EngineApp Engine
App Engine
 
Using Google App Engine Python
Using Google App Engine PythonUsing Google App Engine Python
Using Google App Engine Python
 
Introduction to Google App Engine with Python
Introduction to Google App Engine with PythonIntroduction to Google App Engine with Python
Introduction to Google App Engine with Python
 
Google App Engine for Python - Unit01: Basic
Google App Engine for Python - Unit01: BasicGoogle App Engine for Python - Unit01: Basic
Google App Engine for Python - Unit01: Basic
 
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw  est prêt à tuer le classpathSoft-Shake 2016 : Jigsaw  est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
 
Google datastore & search api
Google datastore & search apiGoogle datastore & search api
Google datastore & search api
 
Google Cloud Platform. Google App Engine
Google Cloud Platform. Google App Engine Google Cloud Platform. Google App Engine
Google Cloud Platform. Google App Engine
 
Google App Engine
Google App EngineGoogle App Engine
Google App Engine
 

Similar to Gae icc fall2011

Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 

Similar to Gae icc fall2011 (20)

Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Java
JavaJava
Java
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
 
JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020
 
Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
maXbox Starter 45 Robotics
maXbox Starter 45 RoboticsmaXbox Starter 45 Robotics
maXbox Starter 45 Robotics
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
More about PHP
More about PHPMore about PHP
More about PHP
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32
 
C#2
C#2C#2
C#2
 
C++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroC++ Windows Forms L01 - Intro
C++ Windows Forms L01 - Intro
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 

More from Juan Gomez

Android Scripting
Android ScriptingAndroid Scripting
Android Scripting
Juan Gomez
 

More from Juan Gomez (6)

App Indexing: Blurring the Lines Between Your Website and App
App Indexing: Blurring the Lines Between Your Website and AppApp Indexing: Blurring the Lines Between Your Website and App
App Indexing: Blurring the Lines Between Your Website and App
 
REST is not enough: Using Push Notifications to better support your mobile cl...
REST is not enough: Using Push Notifications to better support your mobile cl...REST is not enough: Using Push Notifications to better support your mobile cl...
REST is not enough: Using Push Notifications to better support your mobile cl...
 
Beating Android Fragmentation
Beating Android FragmentationBeating Android Fragmentation
Beating Android Fragmentation
 
Effective Android Messaging
Effective Android MessagingEffective Android Messaging
Effective Android Messaging
 
Teach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry PiTeach your kids how to program with Python and the Raspberry Pi
Teach your kids how to program with Python and the Raspberry Pi
 
Android Scripting
Android ScriptingAndroid Scripting
Android Scripting
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Gae icc fall2011

  • 1. Building webapps for the Cloud with Python and Google App Engine Juan Gomez PythonKC Co-founder October 29th, 2011
  • 2. Agenda 1. Intro to Google App Engine (GAE for short) • Brief intro to Python • Structure of a Python webapp • Setting up your dev environment with GAE • App Engine Architecture • The App Engine datastore and GQL 2. Brief intro to Django • Using templates with GAE 3. Quick demo of a sample webapp 4. Beyond the basics • Scalability & Security • Quotas • Using the Google Data Services API 5. Summary • Where to go from here? • References 2
  • 3. Why Google App Engine? Challenges building web apps 3
  • 4. Run your web applications on Google’s infrastructure
  • 7. 1. Scalable Serving Infrastructure 2. Python Runtime 3. Software Development Kit 4. Web based Admin Console 5. Datastore 7
  • 8. 4. Web-based Admin Console 8
  • 10. Memcache Send E-Mail Make HTTP Requests Authenticate with Google Accounts Image Manipulation
  • 11. Does one thing well: running web apps
  • 12. 12
  • 13. 13
  • 14. A Python Code Sample x = 34 - 23 # A comment. y = “Hello” # Another one. z = 3.45 if z is not 3.46 or y is “Hello”: x = x + 1 y = y + “ World” # String concat. print x print y 14
  • 15. Enough to Understand the Code • First assignment to a variable creates it • Assignment is = and comparison is == (or is) • For numbers + - * / % are as expected • Special use: • + for string concatenation • % for string formatting (as in C’s printf) • Logical operators are words (and, or, not) not symbols (&&, ||, !). • The basic printing command is print 15
  • 16. Comments • Start comments with #, rest of line is ignored • Can include a “documentation string” as the first line of a new function or class you define • Development environments, debugger, and other tools use it: it’s good style to include one def my_function(x, y): “““This is the docstring. This function does blah blah blah.””” # The code would go here... 16
  • 17. Python and Types • Everything is an object! • “Dynamic Typing”-> Data types determined automatically. • “Strong Typing” -> Enforces them after it figures them out. x = “the answer is ” # Decides x is string. y = 23 # Decides y is integer. print x + y # Python will complain about this. 17
  • 18. Basic Datatypes • Integers (default for numbers) •z = 5 / 2 # Answer 2, integer division • Floats •x = 3.456 • Strings • Can use “” or ‘’ to specify with “abc” == ‘abc’ • Unmatched can occur within the string: “matt’s” • Use triple double-quotes for multi-line strings or strings that contain both ‘ and “ inside of them: “““a‘b“c””” 18
  • 19. Whitespace Whitespace is meaningful in Python: especially indentation and placement of newlines •Use a newline to end a line of code Use when must go to next line prematurely •No braces {} to mark blocks of code, use consistent indentation instead • First line with less indentation is outside of the block • First line with more indentation starts a nested block •Colons start of a new block in many constructs, e.g. function definitions, then clauses 19
  • 20. Assignment • You can assign to multiple names at the same time >>> x, y = 2, 3 >>> x 2 >>> y 3 This makes it easy to swap values >>> x, y = y, x • Assignments can be chained >>> a = b = x = 2 20
  • 21. A Python Code Sample x = 34 - 23 # A comment. y = “Hello” # Another one. z = 3.45 if z is not 3.46 or y is “Hello”: x = x + 1 y = y + “ World” # String concat. print x print y 21
  • 22. Side by Side with Java Java (C#) Python public class Employee class Employee(): { private String myEmployeeName; private int myTaxDeductions = 1; private String myMaritalStatus = "single"; def __init__(self, employeeName public Employee(String EmployeName) { , taxDeductions=1 this(EmployeName, 1); } , maritalStatus="single" ): public Employee(String EmployeName, int taxDeductions) { this(EmployeName, taxDeductions, "single"); } self.employeeName = employeeName public Employee(String EmployeName, int taxDeductions, self.taxDeductions = taxDeductions String maritalStatus) self.maritalStatus = maritalStatus { this.myEmployeeName = EmployeName; this.myTaxDeductions = taxDeductions; this.myMaritalStatus = maritalStatus; } } 22
  • 23. Life is Short (You Need Python) - Bruce Eckel (Thinking in C++) 23
  • 24. Things to read through: The Quick Python Book, 2nd Ed http://amzn.to/lXKzH5 “Learn Python The Hard Way” http://learnpythonthehardway.org Python 101 – Beginning Python http://www.rexx.com/~dkuhlman/python_101/python_101.html 24
  • 25. Things to refer to: The Python Standard Library by Example http://amzn.to/sx3It1 Programming Python, 4th Ed http://amzn.to/kWjaW2 The Official Python Tutorial http://www.python.org/doc/current/tut/tut.html The Python Quick Reference http://rgruet.free.fr/PQR2.3.html 25
  • 26. 26
  • 28. App Engine Does One Thing Well • App Engine handles HTTP(S) requests, nothing else – Think RPC: request in, processing, response out – Works well for the web and AJAX; also for other services • App configuration is dead simple – No performance tuning needed • Everything is built to scale – “infinite” number of apps, requests/sec, storage capacity – APIs are simple, stupid 28
  • 29. And that allows it to: • Serve static files • Serve dynamic requests • Store data • Call web services • Authenticate against Google’s user database • Send e-mail, process images, use memcache 29
  • 30. Scaling • 5 million page views a month at the free quota • Low-usage apps: many apps per physical host • High-usage apps: multiple physical hosts per app • Stateless APIs are trivial to replicate • Memcache is trivial to shard • Datastore built on top of Bigtable; designed to scale well – Abstraction on top of Bigtable – API influenced by scalability • No joins • Recommendations: denormalize schema; precompute joins 30
  • 31. Python webapps • App Engine includes a simple web application framework called webapp. • webapp is a WSGI-compatible framework. • You can use webapp or any other WSGI framework with GAE (like web.py, CherryPy, Tornado, Django) • Basic apps need Config file + webapp CGI 31
  • 32. Config file (No XML!) • A webapp specifies runtime configuration, including versions and URLs, in a file named app.yaml. application: myapp version: 1 runtime: python api_version: 1 handlers: - url: /admin/.* script: admin.py login: admin - url: /index.html script: home.py - url: /(.*.(gif|png|jpg)) static_files: static/1 upload: static/(.*.(gif|png|jpg)) 32
  • 33. Structure of a Python webapp from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hello, webapp World!') application = webapp.WSGIApplication([('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() 33
  • 34. Setting up your dev environment with GAE • The dev environment is really, really nice • Download the (open source) SDK – http://code.google.com/appengine/downloads.html – Google_App_Engine_SDK_for_Python • a full simulation of the App Engine environment • dev_appserver.py myapp for a local webserver • appcfg.py update myapp to deploy to the cloud • You get a GUI on OS X and Windows. 34
  • 35. App Engine Architecture req/resp stateless APIs R/O FS urlfech Python stdlib VM mail process app images stateful datastore APIs memcache 35
  • 36. The Datastore • Based on “BigTable” • Schemaless • Scales infinitely • NoSQL, with SQL type queries (GQL) – No joins (they do have “reference fields”) – No aggregate queries - not even count()! – Hierarchy affects sharding and transactions – All queries must run against an existing index • Maybe the best part of App Engine! 36
  • 37. Hierarchical Datastore • Entities have a Kind, a Key, and Properties – Entity -> Record -> Python dict -> Python class instance – Key -> structured foreign key; includes Kind – Kind -> Table -> Python class – Property -> Column or Field; has a type • Dynamically typed: Property types are recorded per Entity • Key has either id or name – the id is auto-assigned; alternatively, the name is set by app – A key can be a path including the parent key, and so on • Paths define entity groups which limit transactions – A transaction locks the root entity (parentless ancestor key) 37
  • 38. Creating an Entity in the Datastore from google.appengine.ext import db ... class FoursquareUser(db.Model): """Creation of an entity of the kind 'FoursquareUser'""" created = db.DateTimeProperty(auto_now_add=True) name = db.TextProperty() email = db.TextProperty() description = db.StringProperty(multiline=True) 38
  • 39. GQL • GQL is a SQL-like language for retrieving entities or keys from the datastore. • GQL's features are different from a query language for a traditional relational database. • GQL syntax is (very) similar to that of SQL • SELECT [* | __key__] FROM <kind> [WHERE <condition> [AND <condition> ...]] [ORDER BY <property> [ASC | DESC] [, <property> [ASC | DESC] ...]] [LIMIT [<offset>,]<count>] [OFFSET <offset>] <condition> := <property> {< | <= | > | >= | = | != } <value> <condition> := <property> IN <list> <condition> := ANCESTOR IS <entity or key> 39
  • 40. Querying my FoursquareUser Entity from google.appengine.ext import db ... # I can query the datastore using the Query API query = db.Query(FoursquareUser) # Or the methods inherited form db.Model model_query = FoursquareUser.all() # Or using GQL GQL_query = db.GqlQuery("SELECT * FROM FoursquareUser") # I can print the results to the HTTP response object for user in query: self.response.out.write("User name: %s" % user["name"]) self.response.out.write("User email: %s" % user["email"]) 40
  • 41. Creating the Views • HTML embedded in code is messy and difficult to maintain. • It's better to use a templating system. – HTML is kept in a separate files with special syntax to indicate where the data from the application appears in the view. • There are many templating systems for Python: EZT, Cheetah, ClearSilver, Quixote, and Django are just a few. • You can use your template engine of choice by bundling it with your application code. • Or you can use Django out of the box! 41
  • 43. Why use Django over webapp? • Django templating is one of the best in its class • Django has easy cookies and custom 500 errors • Django is less verbose • Django middleware is really handy • URL patterns – mapping between URL patterns (RegEx) to callback functions (views). – URLconf 43
  • 44. Using templates with GAE from django.conf.urls.defaults import * from django.http import HttpResponse def hello(request): return HttpResponse("Hello, World!") urlpatterns = patterns('', ('^$', hello),) # You have to write even less code! 44
  • 45. Quick demo of a sample webapp 45
  • 46. Automatic Scaling to Application Needs • You don’t need to configure your resource needs • One CPU can handle many requests per second • Apps are hashed (really mapped) onto CPUs: – One process per app, many apps per CPU – Creating a new process is a matter of cloning a generic “model” process and then loading the application code (in fact the clones are pre-created and sit in a queue) – The process hangs around to handle more requests (reuse) – Eventually old processes are killed (recycle) • Busy apps (many QPS) get assigned to multiple CPUs – This automatically adapts to the need • as long as CPUs are available 46
  • 47. Security • Prevent the bad guys from breaking (into) your app • Constrain direct OS functionality – no processes, threads, dynamic library loading (use Task Queue) – no sockets (use urlfetch API) – can’t write files (use datastore) – disallow unsafe Python extensions (e.g. ctypes) • Limit resource usage – Limit 10,000 files per app, adding up to 32 MB – Hard time limit of 60 seconds per request – Daily Max of 6.50 CPU hours (CPU cycles on 1.2 GHz Intel x86) – Hard limit of 32 MB on request and response size, API call size, etc. – Quota system for number of requests, API calls, emails sent, etc 47
  • 48. Preserving Fairness Through Quotas • Everything an app does is limited by quotas. • If you run out of quota that particular operation is blocked • Free quotas are tuned so that a well-written app (light CPU/datastore use) can survive a moderate “slashdotting” • The point of quotas is to be able to support a very large number of small apps. • Large apps need raised quotas ($$$) 48
  • 49. Quotas Costs 49
  • 50. Quotas Quota’s 50
  • 51. Quotas 51
  • 52. Using the Google Data Service API import gdata.docs.service # Create a client class which will make HTTP requests with # Google Docs server. client = gdata.docs.service.DocsService() # Authenticate using your Google Docs email address and # password. client.ClientLogin('joe@gmail.com', 'password') # Query the server for an Atom feed containing a list of your # documents. documents_feed = client.GetDocumentListFeed() # Loop through the feed and extract each document entry. for document_entry in documents_feed.entry: # Display the title of the document on the command line. print document_entry.title.text 52
  • 53. What about vendor Lock-in? 53
  • 54. What about vendor Lock-in? • Use Django-nonrel – independent branch of Django that adds NoSQL database support to the ORM http://www.allbuttonspressed.com/projects/django- nonrel – No JOINs! :-( • Port existing Django projects with very few changes! • Switch from Bigtable to other NoSQL DBs – MongoDB, SimpleDB. (soon Cassandra, CouchDB) • Move freely between Django hosting providers – ep.io, gondor.io, Heroku or your own VPS 54
  • 55. Where to go from here? • Learn Python! • Download the App Engine SDK • Build Apps...Many Apps • Learn Django! (is awesome) • Join a local Python User Group – http://www.pyowa.org or @pyowa on Twitter. – http://pythonkc.com/ or @pythonkc on Twitter. 55
  • 56. Resources • Read the Articles on the Google App Engine site. – http://code.google.com/appengine/docs/python/gettingstarted/ – http://code.google.com/appengine/docs/python/overview.html – http://appengine-cookbook.appspot.com/ • Keep up with new releases through the Blog – http://googleappengine.blogspot.com/ • Read the source code from the SDK – http://code.google.com/p/googleappengine/ – Maybe you will find an undocumented API. 56
  • 57. Things to read through: Programming Google App Engine. (Python & Java) http://amzn.to/ovzX4q 57
  • 58. Before the Q & A... 58
  • 59. Yes! Slides can be downloaded here: http://www.slideshare.net/_juandg/gae_icc_fall2011 59

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. TRAFFIC DATA + CHARTS\n\nAPPLICATION LOGS\n\nMODIFY DATASTORE W/ WEB-BASED INTERFACE\n\nMANAGE ADMINISTRATIVE SETTINGS\n
  9. MAC APPLICATION FOR UPLOADING APPS\nCOMMAND-LINE UTILITY FOR WINDOWS, LINUX, AND MAC\nTHAT&amp;#x2019;S IT, THIS APP WOULD BE SERVING LIVE FROM GOOGLE DATACENTERS\nABLE TO SCALE TO MILLIONS OF USERS\n
  10. MEMCACHE\nSIMPLE COHERENT CACHING LAYER\nSPEEDS UP RESPONSE TIMES FOR COMMON PAGES + QUERIES\n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. A webapp application consists of three parts:\none or more RequestHandler classes (described in Request Handlers)\na WSGIApplication object that maps URLs to RequestHandler classes\na main routine that runs the WSGIApplication using a CGI adaptor\n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. for example:\nrequest count, bandwidth used, CPU usage, datastore call count, disk space used, emails sent, even errors!\n\n(raising an exception) for a while (~10 min) until replenished\n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n