python code camp for professionals 3/4

49
Build a Better Python Web APP

Upload: developers-connect-devcon-philippines

Post on 15-Apr-2017

204 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Python Code Camp for Professionals 3/4

Build a Better Python Web APP

Page 2: Python Code Camp for Professionals 3/4

MongoDB• Much faster than SQL databases

• No need to learn query languages* and setups

• Easier to scale when designed properly

Page 3: Python Code Camp for Professionals 3/4

Install pymongopip install pymongo

easy_install pymongo

Page 4: Python Code Camp for Professionals 3/4

Hello Worldfrom pymongo import MongoClient

client = MongoClient("localhost", 27017)db = client.databasename

Page 5: Python Code Camp for Professionals 3/4

Stepfrom pymongo import MongoClientImport MongoClient from pymongo

client = MongoClient("localhost", 27017)Connect to the mongodb server at the IP address and port defined

db = client.databasenameAccess a specific database in the mongodb server

collection = db.collectionnameAccess a specific collection (table in SQL) in the selected db

Page 6: Python Code Camp for Professionals 3/4

Basic DB Operations

•Create

•Read

•Update

•Delete

Page 7: Python Code Camp for Professionals 3/4

Create@route("/user/list")def listuser():

usercursor = db.users.find({},{"_id":False})users = list(usercursor)return {"users":users}

Page 8: Python Code Camp for Professionals 3/4

Stepusercursor = db.users.find({},{"_id":False})Find all entries in the collection named users and do not show the _id field

users = list(usercursor)Convert the cursor object into a list, which we can be converted to a json object

return {"users":users}Return the list of users to the browser

Page 9: Python Code Camp for Professionals 3/4

The Query Formatdb.collectionname.find(filter,projection) Filter is the expression that needs to be true an element to be includedExamples:• {} = will return all• {“name”:”paolo”} = will only return entries with name

exactly to “paolo”• {“name”:”paolo”, “age”:{“$lte”:30}} = will only return

entries with names exactly “paolo” and age is less than or equal to 30

See more filter operators here: https://docs.mongodb.com/manual/reference/operator/query/

Page 10: Python Code Camp for Professionals 3/4

ReadVia query string@route('/sum')def sum(): total = 0 start = request.query.get("start") end = request.query.get("end") for i in range(start,end): total += i return "Sum of "+str(start) + " to " + str(end) + " = " + str(total)

Visit: localhost:8001/sum?start=1&end=10

Page 11: Python Code Camp for Professionals 3/4

Inputs in BottleVia POST body@route('/login', method="POST")def login(): username = request.forms.get("username") password = request.forms.get("password") acceptedpasswords = ["gloopgroup", "devconph" , "adventuretime"] if password in acceptedpasswords: return "Welcome "+ username else: return "Unauthorized"

Visit: localhost:8001/login using login page

Page 12: Python Code Camp for Professionals 3/4

Activity 1Create a calculator api:http://localhost:8001/operation/operand1/operand2will return the value ofoperand1 <operation> operand2

Example:/subtraction/10/2 will output 8

Page 13: Python Code Camp for Professionals 3/4

Common Return TYPESPlain TextSimilar to what we were doing earlier

Page 14: Python Code Camp for Professionals 3/4

Common Return TYPESBinaryWhen returning files like images, video, audio, pdfs…

Page 15: Python Code Camp for Professionals 3/4

Common Return TYPESJSONThe common return type for APIsExample: FB API/{userid}/friends

{ "data": [ { "name": "Terence Pua", "id": "608407" }, { "name": "Gene Paul Quevedo", "id": "10153785024974240" }, { "name": "Jc Velasquez", "id": "722462218" }, { "name": "Jomel C. Imperio", "id": "779287017" } ], "summary": { "total_count": 770 }}

Page 16: Python Code Camp for Professionals 3/4

Common Return TYPESHTMLReturn web pages with dynamic/static content<!DOCTYPE html><html itemscope itemtype="http://schema.org/QAPage"><head>

<title>regex - Validate email address in JavaScript? - Stack Overflow</title> <link rel="shortcut icon" href="//cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico?v=4f32ecc8f43d"> <link rel="apple-touch-icon image_src" href="//cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a"> <link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml"> <meta name="twitter:card" content="summary"> <meta name="twitter:domain" content="stackoverflow.com"/> <meta property="og:type" content="website" />

<meta property="og:image" itemprop="image primaryImageOfPage" content="http://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]?v=73d79a89bded&a" /> <meta name="twitter:title" property="og:title" itemprop="title name" content="Validate email address in JavaScript?" /> <meta name="twitter:description" property="og:description" itemprop="description" content="How can an email address be validated in JavaScript?" /> <meta property="og:url" content="http://stackoverflow.com/questions/46155/validate-email-address-in-javascript"/> <link rel="canonical" href="http://stackoverflow.com/questions/46155/validate-email-address-in-javascript" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="//cdn.sstatic.net/Js/stub.en.js?v=d33f759d1183"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/stackoverflow/all.css?v=a13f0e8d2a4f">

<link rel="alternate" type="application/atom+xml" title="Feed for question &#39;Validate email address in JavaScript?&#39;" href="/feeds/question/46155"> <meta name="twitter:app:country" content="US" /> <meta name="twitter:app:name:iphone" content="Stack Exchange iOS" /> <meta name="twitter:app:id:iphone" content="871299723" /> <meta name="twitter:app:url:iphone" content="se-zaphod://stackoverflow.com/questions/46155/validate-email-address-in-javascript" /> <meta name="twitter:app:name:ipad" content="Stack Exchange iOS" /> <meta name="twitter:app:id:ipad" content="871299723" /> <meta name="twitter:app:url:ipad" content="se-zaphod://stackoverflow.com/questions/46155/validate-email-address-in-javascript" /> <meta name="twitter:app:name:googleplay" content="Stack Exchange Android"> <meta name="twitter:app:url:googleplay" content="http://stackoverflow.com/questions/46155/validate-email-address-in-javascript"> <meta name="twitter:app:id:googleplay" content="com.stackexchange.marvin"> <script>

Page 17: Python Code Camp for Professionals 3/4

Returning JSON ObjectJSONSimply return a dictionary or list@route("/json")def jason(): return {"lastname":"bourne", "alias":"David Webb"}

Page 18: Python Code Camp for Professionals 3/4

Returning Static HTMLHTMLUse static_file from bottle@route("/loginpage")def loginpage(): return static_file("login.html", root=".")

Page 19: Python Code Camp for Professionals 3/4

Testing the POST Handler

Visit localhost:8081/loginpage

Type your name and use any of these as passwordggloopgroup, devconph, adventuretime

Click submit

Page 20: Python Code Camp for Professionals 3/4

The POST Request Cycle<form action="/login" method="POST">Method dictates what kind of request happens when submittedAction tells the browser where to submit the request

<input type="text" name="username">Adds a text input that will be associated to the username field

<input type="password" name="password">Adds a password input that will be associated to the password field

<input type="submit">Adds a button that submits the form when clicked

Page 21: Python Code Camp for Professionals 3/4

Returning Dynamic HTMLHTMLUse a templating engine:• Library that can substitute variables into a template quickly and cleanly• Isolates the designer’s job of designing and the coder’s job of coding

Page 22: Python Code Camp for Professionals 3/4

Install Tenjinpip install tenjin

easy_install tenjin

Page 23: Python Code Camp for Professionals 3/4

Using Tenjinfrom gevent import monkey; monkey.patch_all()from bottle import run, route, requestimport tenjinfrom tenjin.helpers import *

@route("/introduction/<name>/<age>/<work>")def template1(name, age, work):

context = {"name":name, "age":age, "work":work}return engine.render("introduction.html", context);

engine = tenjin.Engine(path=['.'])run(server='gevent', host="localhost", port=8001, debug=True)

Page 24: Python Code Camp for Professionals 3/4

The template<!doctype html><html lang="en"><head>

<title>Login</title></head><body>

<h1>${name}</h1><h2>Age:${age}<h2><h2>Work:${work}<h2>

</body></html>

Page 25: Python Code Camp for Professionals 3/4

Stepfrom gevent import monkey; monkey.patch_all()from bottle import run, route, requestimport tenjinfrom tenjin.helpers import *Import all libraries, including tenjin and all helper methods

@route("/introduction/<name>/<age>/<work>")Define a route for the url, and define variables in it

def template1(name, age, work):Declare a request handler and receive the variables from the url

Page 26: Python Code Camp for Professionals 3/4

Stepcontext = {"name":name, "age":age, "work":work}Define a context variable, which is a dictionary of values that will be substituted into the template

return engine.render("introduction.html", context);Render the template called introduction.html using the context variable named context, and return it to the browser

engine = tenjin.Engine(path=['.'])Instructs the templating engine to look for the templates in the directories listed in path

Page 27: Python Code Camp for Professionals 3/4

Step (Inside the template)

<!doctype html><html lang="en"><head>

<title>Login</title></head><body>

<h1>${name}</h1><h2>Age:${age}<h2><h2>Work:${work}<h2>

</body></html>

{"name":"Paolo", "age":"30", "work":"Synergist"

}+

Page 28: Python Code Camp for Professionals 3/4

Displaying Lists@route("/spell/<word>")def template1(word):

letters = list(word)context = {"letters":letters, "word":word}return engine.render("speller.html", context);

Page 29: Python Code Camp for Professionals 3/4

Step@route("/spell/<word>")Define a route that accepts a variable assigned to word

def speller(word):Define a handler that accepts a variable named word

letters = list(word)Convert the text string into a list object. From a string “word”, it becomes a list [“w”, “o”, “r”, “d”]

Page 30: Python Code Camp for Professionals 3/4

Stepcontext = {"letters":letters}Define a context variable, which contains the list of letters we just created

return engine.render("speller.html", context);Render the template called speller.html using the context variable named context, and return it to the browser

Page 31: Python Code Camp for Professionals 3/4

Step (Inside the template)

<?py for letter in letters: ?>Loop on the elements of the list named letters

<h3>${letter}</h3><br>Display the element letter along with the html

<?py #endfor ?>Denote where the loop ends in the template

<a href="/greet/${word}">greet ${word}</a>Create a link that will call the greet API we created earlier

{"letters":["s", "u", "s", "h", "i"]}

Page 32: Python Code Camp for Professionals 3/4

Highlighting Names@route("/profiles/<name>")def profile(name):

users = [{"name":"Em", "image":"http://goo.gl/aDxeu1",

"age":30, "work":"Futurist"},{"name":"Paolo",

"image":"http://goo.gl/5k2oZr", "age":30, "work":"Synergist"}]

context = {"users":users, "name":name}return engine.render("profiles.html", context)

Page 33: Python Code Camp for Professionals 3/4

Stepusers = [

{"name":"Em", "image":"http://goo.gl/aDxeu1", "age":30,

"work":"Futurist"},{"name":"Paolo", "image":"http://goo.gl/5k2oZr", "age":30,

"work":"Synergist"}

] Define a list of dictionaries, with each dictionary object containing information about a user. It contains information name, url of the image, age, and work

context = {"users":users, "name":name}Define a conext containing the name to be highlighted, and the list of users

return engine.render("profiles.html", context) Render the template named profiles.html with the context

Page 34: Python Code Camp for Professionals 3/4

Step (Inside the template)<?py for user in users: ?> Loop on the elements of the list named users, each element in the list can be referred to using the user variable

<div style="height:100px;"> Create a div element in the html to contain one user element

<img src="${user['image']}" style="float:left; height:100%;"/> Place an image in the html coming from the url defined in user[‘image’]

Page 35: Python Code Camp for Professionals 3/4

Step (Inside the template)<?py if name==user["name"]: ?>Compare the current user’s name to the name entered in the url

<strong>Name: ${user['name']}</strong>This happens when the above condition is true, display the name as bold characters

<?py else: ?>Add an else handler that executes if condition is not met

Page 36: Python Code Camp for Professionals 3/4

Step (Inside the template)Name: ${user['name']}This happens when primary condition is not met, display the user’s name without any decorations

<?py #endif ?>Denote where the if statement ends

Page 37: Python Code Camp for Professionals 3/4

Make a Sushi MenuCreate a menu using all the sushi items in the sushilist variable

Display the image and name of the sushi

When the menu item is clicked, it should display another page containing the name, image, price, and rating of the sushi (defined in the sushilist variable)

The most creative presentation of the menu wins a prize

Page 38: Python Code Camp for Professionals 3/4

Activity 1pip install geventpip install bottle

Page 39: Python Code Camp for Professionals 3/4

Cost per Mille =• Cost per 1000 impressions• Abuse of statistics• i.e. Magic• i.e. It sucks• Not based on empirical measured data

ADVERTISING!

Eyeballscost

Page 40: Python Code Camp for Professionals 3/4

How many are watching me right now?How many are paying attention?How many are interested?How many are still reading this part?How about now?Now?

Page 41: Python Code Camp for Professionals 3/4
Page 42: Python Code Camp for Professionals 3/4

ROUTER ON PROMISCUOUS MODE

DEVICEs SENDING PROBE REQUESTS

Page 43: Python Code Camp for Professionals 3/4

PYTHON+TCPDUMP

We get this

Page 44: Python Code Camp for Professionals 3/4

Pilot Installation

23000Passers-by

39%viewed

10%Finished

Page 45: Python Code Camp for Professionals 3/4

Meh…

Page 46: Python Code Camp for Professionals 3/4

Map movement

Page 47: Python Code Camp for Professionals 3/4

Geofencing alternative

Detectionperimeter

Page 48: Python Code Camp for Professionals 3/4

snoop

Page 49: Python Code Camp for Professionals 3/4

turn off your phones when going to the lagoon