You are on page 1of 26

Programming IoT

Lesson 3

Python introduction

OBJECT PRACTICING

Reference
http://learnpythonthehardway.org/
Exercize 40-41-42

How to use modules

Imagine I have a module that I decide to name mystuff.py and I put a function in it called apple. Here's
the module mystuff.py:

# this goes in mystuff.py


def apple():
print "I AM APPLES!"

Once I have this code, I can use the module MyStuff with import and then access the apple function:

import mystuff
mystuff.apple()

I could also put a variable in it named tangerine:

def apple():
print "I AM APPLES!
# this is just a variable
tangerine = "Living reflection of a dream

I can access that the same way:

import mystuff
mystuff.apple()
print mystuff.tangerine

Classes are like modules and


objects are like import
class MyStuff(object):
def __init__(self):
self.tangerine = I am learning OOP
def apple(self):
print "I AM CLASSY APPLES!

You can take this MyStuff class and use it to instatiate many of them.
When you import a module there is only one for the entire program.
You instantiate (create) a class by calling the class like it's a function, like this:

thing = MyStuff()
thing.apple()
print thing.tangerine

Python looks for MyStuff() and sees that it is a class you've defined.
Python create an empty object with all the functions you've specified in the class using def.
Python then looks to see if you there is a __init__ function, and if there is, it calls that function to initialize
your newly created empty object.
In the MyStuff function __init__ there is an extra variable self, which is that empty object Python made, for
instance to set variables on it.
In this case, I set self.tangerine to a string and then I've initialized this object.
Now Python can take this newly created object and assign it to the thing variable.

Getting things
I now have three ways to get things from things:
# dict style
mystuff['apples']
# module style
mystuff.apples()
print mystuff.tangerine
# class style
thing = MyStuff()
thing.apples()
print thing.tangerine

Class example
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line

The __init__
method is called
passing lyrics as
parameter

happy_bday = Song(["Happy birthday to you,


"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around tha family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

Output:
$ python ex40.py
Happy birthday to you
I don't want to get sued
So I'll stop right there
They rally around tha family
With pockets full of shells

Inheritance example
class Parent(object):
def implicit(self):
print "PARENT implicit()"
class Child(Parent):
pass
dad = Parent()
son = Child()
dad.implicit()
son.implicit()

The use of pass under the class Child: is how you tell Python that you want an empty block.

This creates a class named Child but says that there's nothing new to define in it.

Instead it will inherit all of its behavior from Parent.

Output:
$ python ex44a.py
PARENT implicit()
PARENT implicit()

Override

The problem with having functions called implicitly is sometimes you want the child to behave differently.

In this case you want to override the function in the child, effectively replacing the functionality.

To do this just define a function with the same name in Child.

Here's an example:
class Parent(object):
def override(self):
print "PARENT override()"
class Child(Parent):
def override(self):
print "CHILD override()"
dad = Parent()
son = Child()
dad.override()
son.override()

In this example I have a function named override in both classes, so let's see what happens when you
run it.

Output:
$ python ex44b.py
PARENT override()
CHILD override()

A more confusing example

The third way to use inheritance is a special case of overriding where you want to alter the behavior
before or after the Parent class's version runs.

You first override the function just like in the last example, but then you use a Python built-in function
named super to get the Parent version to call.

Here's the example of doing that so you can make sense of this description:
class Parent(object):
def altered(self):
print "PARENT altered()"
class Child(Parent):
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
dad = Parent()
son = Child()
dad.altered()
son.altered()

Output:
$ python ex44c.py
PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()

Using super() with __init__

The most common use of super() is actually in __init__ functions in base


classes.
This is usually the only place where you need to do some things in a child,
then complete the initialization in the parent.
Example:

class Child(Parent):
def __init__(self, stuff):
self.stuff = stuff
super(Child, self).__init__()

Python introduction

WEB PROGRAMMING

Reference
http://learnpythonthehardway.org/
Exercizes 50-51
Use libthw.py or web.py for this part
See exercize 50 for installation instructions

First website

Put the following code into bin/app.py:

Your browser makes a network connec;on to your own


computer, which is called localhost on port 8080.

import web

Once it connects, it makes an HTTP request to the bin/


app.py applica;on and asks for the / URL, which is
commonly the rst URL on any website.

app = web.application(urls,
Inside bin/app.py you've got a list of URLs and what classes
globals())
they match. The only one we have is the '/', 'index'
mapping. This means that whenever someone goes to /
class index:
with a browser, lpthw.web will nd the class index and
def GET(self):
greeting = "Hello World"
load it to handle the request.
urls = (
'/', 'index'
)

return greeting

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

Then run the application like this:

$ python bin/app.py
http://0.0.0.0:8080/

Now that lpthw.web has found class index it calls the


index.GET method on an instance of that class to actually
handle the request. This func;on runs and simply returns a
string for what lpthw.web should send to the browser.

Finally, lpthw.web has handled the request and sends this
response to the browser, which is what you are seeing.

Basic templates

The first step is to create a templates/index.html file that looks like this:

$def with (greeting_var)


<html>
<head>
<title>IoT Programming Course</title>
</head>
<body>
$if greeting_var:
I just wanted to say <em style="color: green; font-size: 2em;">$greeting_var</em>
$else:
<em>Hello</em>, IoT programmers!
</body>
</html>

This HTML file is a template, which means that lpthw.web will fill in "holes" in the text depending on variables
you pass in to the template. Every place you see $greeting will be a variable you'll pass to the template that
alters its contents.

Managing Templates

To make your bin/app.py do this, you need to add some code to tell lpthw.web where to load the template
and to render it. Take that file and change it like this:

import web
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
greeting = "Hello World"
return render.index(greeting_var = greeting)
if __name__ == "__main__":
app.run()

Pay close attention to the new render variable and how I changed the last line of index.GET so it returns
render.index() passing in your greeting variable.

Explanation

In your bin/app.py you've added a new variable, render, which is a web.template.render


object.

This render object knows how to load .html files out of the templates/ directory because you
passed that to it as a parameter.

Later in your code, when the browser hits the index.GET like before, instead of just
returning the string greeting, you call render.index and pass the greeting to it as a variable.

This render.index method is kind of a magic function where the render object sees that
you're asking for index, goes into the templates/ directory, looks for a page named
index.html, and then "renders" it, or converts it.

In the templates/index.html file you see the beginning definition that says this template
takes a greeting parameter, just like a function. Also, just like Python this template is
indentation sensitive, so make sure you get them right.

Finally, you have the HTML in templates/index.html that looks at the greeting variable and,
if it's there, prints one message using the $greeting, or a default message.

How the web works

Please refer to learnpythonthehardway.org for more info

GET request path: A -> B -> C -> D


HTML le path: D -> C -> B -> A

HTML Forms

The best way to play with forms is to write some code that accepts form data, and then see what you can do. Take your bin/app.py file
and make it look like this:
import web
urls = (
'/hello', 'Index'
)

app = web.application(urls, globals())

This input is passed


as part of the URL

render = web.template.render('templates/')
class Index(object):
def GET(self):
form = web.input(name="Nobody")
greeting = "Hello, %s" % form.name
return render.index(greeting_var = greeting)
if __name__ == "__main__":
app.run()

Going to http://localhost:8080/hello it should display, "I just wanted to say Hello, Nobody."

Next, change the URL in your browser to http://localhost:8080/hello?name=Andrea and you'll see it say, "Hello, Frank." Finally, change
the name=Frank part to be your name. Now it's saying hello to you.

Use web.input to get data from the browser. This function takes a key=value set of defaults, parses the ?name=Andrea part of the URL
you give it, and then returns a nice object for you to work with that represents those values.

The greeting is built from the new form.name attribute of the form object.

Creating Forms with POST


"POST form is a special HTML file that has a <form> tag in it.
This form will collect information from the user, then send it to your web
application

You should then change bin/app.py to look like this:

Here's the new HTML file you need to create, in templates/


hello_form.html:

urls = (
'/hello', 'Index'
)

<html>
<head>
<title>Sample Web Form</title>
</head>
/hello is the URL
<body>
<h1>Fill Out This Form</h1>

running the form


POST is the method

<form action="/hello" method="POST">


A Greeting: <input type="text" name="greet">
<br/>
Your Name: <input type="text" name="name">
<br/>
<input type="submit">
</form>
</body>
</html>

Note that GET returns


hello_form.html,
while POST returns
index.html

import web

/hello must be in the


list of URLs

app = web.application(urls, globals())


render = web.template.render('templates/')
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="Nobody",
greet="Hello")
greeting = "%s, %s" % (form.greet,
form.name)
return render.index(greeting_var =
greeting)
if __name__ == "__main__":
app.run()

How POST works


Execu;on:
index.GET
hYp://localhost:8080

index.POST
GET method

1.

The browser first hits the web application at /hello but it sends a GET, so our index.GET function runs and returns
the hello_form.

How POST works


hYp://localhost:8080

index.POST
hello_form.html

1.

The browser first hits the web application at /hello but it sends a GET, so our index.GET function runs and returns
the hello_form.

How POST works


hYp://localhost:8080

POST method:
name=greet,
name=name

index.POST

1.

The browser first hits the web application at /hello but it sends a GET, so our index.GET function runs and returns
the hello_form.

2.

You fill out the form in the browser, and the browser does what the <form> says and sends the data as a POST.

How POST works


Execu;on:
index.POST
hYp://localhost:8080

POST method:
name=greet,
name=name

index.POST

1.

The browser first hits the web application at /hello but it sends a GET, so our index.GET function runs and returns
the hello_form.

2.

You fill out the form in the browser, and the browser does what the <form> says and sends the data as a POST.

3.

The web application then runs the index.POST method rather than the index.GET method to handle this request.

How POST works


hYp://localhost:8080

index.POST
index.html

1.

The browser first hits the web application at /hello but it sends a GET, so our index.GET function runs and returns
the hello_form.

2.

You fill out the form in the browser, and the browser does what the <form> says and sends the data as a POST.

3.

The web application then runs the index.POST method rather than the index.GET method to handle this request.

4.

This index.POST method then does what it normally does to send back the hello page like before.

References
http://learnpythonthehardway.org/
http://www.htmldog.com/guides/
http://www.webpy.org/tutorial3.en

You might also like