Learn » Intro-Projects » Python Dojo.md

Coding Dojo December 2014

This dojo will be done a bit differently. The problem will be more practical and unlike a normal dojo we encourage you to keep your solution to project I for project II

You will be paired up to work on the Phase I from 7 to 7:45. We will have a 15 minute group discussion, change partners, and work either on project II or more on project I.

Everyone one is at different level, if you can't figure out something together ask another pair or ask the facilitators. The idea is we will all learn something by the end of the night and learn at our pace.

Setup pip

This dojo will make use of 3rd party libraries which don't come with Python. There is a whole ecosystem of interesting libraries you can make use of and once pip is setup it isn't too hard to access them.

Setting up pip is still a bit challenging. If you run into a problem please ask some one to help you. We will present two methods, pip 2014 and the direct way.

pip 2014

You can follow the instructions here if you are using a Mac or Linux

https://pip2014.com/

You won't need virtualenv or a C compiler for this dojo, but some libraries do require you to be able to compile some code on your laptop.

Assuming the app/script ran correctly you should be able to test it out, check the "Success" section below

The pip 2014 app/script makes it so you don't have to pass --user to pip when installing packages, but since not everyone will be install pip this way the flag will be in our examples.

pip Direct

To install pip the direct way try this one liner on your command prompt under either Mac OS X or Linux:

$ curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python

This will download the get-pip.py script and run it with Python. On Windows you can download get-pip.py another way and then just execute it with Python.

$ python get-pip.py

If it ran successfully you should be able to test pip by following the instructions in the "Success" section.

This way of installing pip doesn't change other things on your laptop like your PATH. When you install a 3rd party library which provides an excutable command with the --user flag you won't be able to run it easily until you modify your PATH. Tonight we won't be installing any libraries which provide a command, but Django's django-admin.py would be an example of command you would want to be able to access after you installed Django.

On Windows another option which should work in a pinch is easy_install pip.

Success

You should be able to run the following without an error

$ pip install --user requests
...
$ python
...
>>> from requests import get
>>> response = get('http://google.com')
>>> response
<Response [200]>

Project 1: Access Open Data

Programs are great working with data. The Internet is a great source of data to experiment with if you can get it in the right format. Fortunately the open data movement makes it easier.

We will be using the Requests Python library to access a web based open data API from the University of Waterloo.

If you tested pip in the "Success" section above when you already have it. If not use pip to install it.

$ pip install --user requests

Once Requests is installed it becomes very easy in Python to get the content of webpages. Web APIs tend to provide data in a format called JSON which is similar to Python dictionaries and list. Requests has an easy way to convert JSON data to Python. Try this example:

$ python
>>> from requests import get
>>> response = get('https://api.uwaterloo.ca/v2/events/holidays.json')
>>> data = response.json()
>>> print(data)

Your goal is to write a Python function which you can call to find out if today is a holiday at the University of Waterloo or not. Start by making a file called holiday.py and copy this into it:

import datetime
from requests import get

def is_holiday():
    # TODO: call the open data api, figure out what today is and check to see if today is a holiday
    # return True if it is and False if it isn't.
    pass


if __name__ == "__main__":
   if is_holiday():
       print("It is a holiday at UW, no school today!")
   else:
       print("Not a holiday today, you have to go to school.")

Dates and Times in Python

Handling time is actually one of the harder problems in programming. Most languages provide built in libraries to help and so does Python, a few actually. We recommend you use the datetime library.

>>> import datetime
>>> today = datetime.date.today()
>>> today.year

Success

If you have successfully implement your function you should be able to do this:

$ python holiday.py
Not a holiday today, you have to go to school.

You will have to wait until the Christmas break to see the other output option :).

Instead of writing the function all at once start by making it always return True or False and then get it to print the current date. You can keep running the script to test your progress.

Project 2: Simple Dynamic Website

Using the command line isn't the most intuitive. A more flexible interface is the web, and it pretty easy to write and run website on your own computer which interact with a open data API or even your own laptop.

There are a few different Python web frameworks but the easiest to get started with Flask. Like with Requests you can use pip to install Flask

$ pip install --user flask

With Flask installed let's create the file web_interface.py beside holiday.py can start by copying the example flask provides:

# web_interface.py
from flask import Flask
app = Flask(__name__)

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

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

You can run your own small self contained website with this command:

$ python web_interface.py
 * Running on http://localhost:5000/

The output of running web_interface.py is a bit strange. When you run it, it doesn't return you to a command prompt, and it doesn't output "Hello World!" instead it lets you know that if you open a browser and put "http://localhost:5000/" into the URL bar you will be take to a webpage generated by this Python script. Try it out!

When you make a change you will want to restart the website, also when you are done you will probably want to stop it. Go into your command line where you see output like this:

$ python web_interface.py 
 * Running on http://127.0.0.1:5000/
127.0.0.1 - - [15/Dec/2014 17:12:48] "GET / HTTP/1.1" 200 -

And type control-c that is hold down the control key and type the c key. You know it has worked when you see a prompt again.

$ python web_interface.py 
 * Running on http://127.0.0.1:5000/
127.0.0.1 - - [15/Dec/2014 17:12:48] "GET / HTTP/1.1" 200 -  
^C$

Now when you go back to your web browser and try to reload you page you will see that it can't find it.

HTML

The web is built on a markup language called HTML, we won't go into too much detail here, but combining HTML with Python enables you to create dynamic websites. Let's use triple quoted string in Python to output some HTML.

# web_interface.py
from flask import Flask
app = Flask(__name__)

html = '''
<html>
<head>
<title>My Dynamic Website</title>
</head>
<body>
<h1>{}</h1>
</body>
</html>
'''

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

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

Run web_inteface.py again and checkout the difference. html holds a string of text which is a template we are using to render our webpage. The {} placeholder is populated with the value "Hello World!" via the format function on strings.

Bring it together

Your final task is to take your is_hoilday function from Project 1 and combine it with your dynamic website. Make a website which will tell you if today is a holiday at the University of Waterloo or not.