A recipe for App Engine – Target – How does it work



A recipe for App Engine – Target – How does it work

0 0


flask-on-appengine

The slides for Python Meetup Barcelona about flask in Google App Engine

On Github merqurio / flask-on-appengine

A recipe for App Engine

Gabi de Maeztu http://merqur.io

Target

  • Build an interface for your scripts.
  • A tool non web developers.

The [ideal] solution

  • Easy
  • Fast to build
  • Free or almost
  • No maintenance

What is flask

  • Flask is a web microframework
  • Based on Werkzeug (WSGI), Jinja 2
  • It's BSD licensed

Why flask

  • Nobody* has time to properly test the framework and read the code
  • Learn as you go *Almost

flask is simple

						
from flask import Flask

app = Flask(__name__)

@app.route("/")
@app.route("/home/")
def hello():
	return "Hello World!"

if __name__ == "__main__":
	app.run()
						
					

That easy

What flask does

  • Built in dev server and debugger
  • Routing
  • Template rendering
  • Access request data
  • Manage sessions
  • [ . . . ]

What flask doesn't

  • Automated admin interface
  • Authentication
  • l10n / i18n
  • Syndication feeds (RSS/Atom)
  • Sitemaps
  • It's not Django (❤) Nor intends.

How does it work

HTTP & WWW

HTTP Request

HTTP Response

MVC

  • M ⇒ "Model"
  • V ⇒ View
  • C ⇒ Controller

MVC [1]

MVC [2]

MVC [3]

Views [1]

  • Whatever you want to return
  • Text
  • HTML, JSON
  • Other crazy stuff [. . .]

Views [2]

Templates:

Used to render the HTML content of the page that the user ultimately sees

Views [3]

						
from flask import render_template

@app.route('/hello/')
@app.route('/hello/< name>')
def hello(name=None):
	return render_template('hello.html', name=name)
						
					

Views [4]

						

Hello from Flask
{% if name %}

Hello {{ name }}!

{% else %}

Hello World!

{% endif %}

Easy to setup

						
$ pip install flask
						
					

Even nicer if we use virtualenv, so our libraries do not mess up

						
$ mkdir flask

$ virtualenv flask/
	New python executable in flask/bin/python3.4
	Also creating executable in flask/bin/python
	Installing setuptools, pip, wheel...done.

$ . flask/bin/activate
(flask)$ cd flask/
(flask)$ pip install flask
						
					

now what ?

  • Create an app.py file
  • Start a Flask instance
						
# import the framework
from flask import Flask

# create an instance
app = Flask(__name__)

# define a route and a 'controller'
@app.route("/")
def hello():
	return "Hello World!"

# if runing this script, start up dev server
if __name__ == "__main__":
	app.run()
						
					

Run it

						
$ python hello.py
	* Running on http://localhost:8000/
						
					

Let's build a rocket

Google App Engine

What is it ?

  • PASS | Platform as a Service
  • Java, Python, Go, PHP
  • Python 2.7.3
  • Replicated over the Google servers
  • Resources depend on need ⇒ Flexible billing

Pros

  • Scalable
  • Easy and cheap
  • Nice option for start-ups/individuals
  • Zero maintenaince
  • Lot of APIs (Email, Image, DB [. . .])
  • Free quota per day1 GB Traffic,50k read/write to DB, 5GB Store

Cons

  • Not for CPU intensive apps
  • Can't use libraries with non python code
  • No multithreading
  • Locked to App Engine ? (AppScale)
  • Not an easy filesystem

Workflow

Install the platform Create an app.yaml Develop and Test Deploy

GAE Installation

						
$ curl https://sdk.cloud.google.com | bash

or

$ docker pull google/cloud-sdk
						
					

Flask ❤ App Engine

Using GAE skeleton

  • In a Git repository (link)
  • Adds libraries in /lib to path
  • Libraries in /lib will be uploaded

Let's start a project

						
$ git clone https://github.com/GoogleCloudPlatform/appengine-python-flask-skeleton

$ cd appengine-python-flask-skeleton

$ pip install -r requirements.txt -t lib
						
					

Let's start a project [2]

console.developers.google.com

Configuration file

						
application: flask-pybcn #your app id here
version: 1
runtime: python27
api_version: 1
threadsafe: yes

- url: .* # This regex directs all routes to main.app
	script: main.app

						
					

main.py

						
# Import the Flask Framework
from flask import Flask
app = Flask(__name__)

# We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.

@app.route('/')
def hello():
	return 'Hello World!'
						
					

Run locally or Deploy

						
$ dev_appserver.py .  # Run's a server at localhost:8080

$ appcfg.py -A project-id update . # Deploy to App Engine
						
					

Deployment

Available at project-id.appspot.com

Flask on esteroids

NDB Datastore

						
from google.appengine.ext import ndb

class Publication(ndb.Model):
    """A publication object."""
    date = ndb.DateTimeProperty(auto_now_add=True)
    title = ndb.StringProperty(required=True)
    pages = ndb.IntProperty()
    year = ndb.DateTimeProperty()
    is_book = ndb.BooleanProperty()
						
					

NDB Datastore [2]

						
little_prince = Publication(title='The Little Prince')
little_prince.pages = 112
little_prince.year = datetime.date(1943, 04, 06)
little_prince.is_book = True

little_prince.put()
						
					

NDB Datastore [3]

  • ACID transactions
  • Easy to use
  • Replicated and scaled automatically
  • Automatic cache of most requested transactions

Creating an Interface

								

	
								
							

Creating an Interface [2]

						
@app.route('/')
def index():
    return render_template('index.html')

						
					

Creating an Interface [3]

						
from models import Publication

@app.route('/', methods=['GET', 'POST'])
def index():
	if request.method == 'POST':

		little_prince = Publication()
		little_prince.title = request.form['title']

		little_prince.put()

	return render_template('index.html')

						
					

Creating an Interface [4]

						
@app.route('/', methods=['GET', 'POST'])
def index():
  if request.method == 'POST':
    little_prince = Publication()
    little_prince.title = request.form['title']

	little_prince.put()

  all_pub = Publication.query().fetch()

  return render_template('index.html', pubs=all_pub)

						
					

Creating an Interface

Jinja templating
						
{% for publication in pubs %}
	

{{ publication.title }}

{{publication.pages}} {% endfor %}

Rocket Science 101

Real world examples

That's all folks!

Flask Google App Engine Explore Flask Follow me ! @gabimaeztu

A recipe for App Engine Gabi de Maeztu http://merqur.io