Code Toolkit: Python, Fall 2020

Week 14 — Wednesday, December 9 — Class notes

Putting things together

This lesson is going to review things that we have already talked about, since week 11, but stitching them together in a way that will be a bit more clear and directly applicable to the work you will be doing for your final project.

Step 1. week14_inclass1.pyde

Look at what the URL looks like when submit the Mad Lib form. It looks something like this:

  http://127.0.0.1:8000/cgi-bin/server.py?name=Gritty&species=monster
All the text in blue is called a query string. It comprises a list of key-value pairs that the client sends to the server. We can use this same format whether it is a web browser submitting an HTML form or a Processing program making a network request. The query string is comprised of one or more parameters, very similar to the parameters or arguments that you pass to a function when you invoke a Python or Processing command, but the syntax is quite different.

In this case, each parameter is separated by an ampersand (&). The key is specified by name, then an equal sign, then the value. So the above reqest is sending two key-value pairs to the server:

This principle is how your Processing code or web-based data entry interface will submit user data to the server.

Step 2. This code adds a unique ID that we will submit with our data so the server can save the data for each client uniquely. It also adds a new tab called network. For now, this will implement a function that will make the network send that data to the server. That tab includes a variable called lastSend that it uses to limit (or "throttle") requests to once per second. You can adjust the timing here to experiment with the timing and interaction of your own project — but be mindful that the framerate of a Processing sketch (probably 30-60 frames per second) is much faster than you would probably want to make requests over a network, unless you were working with a more specialized protocol that was designed to handle many more requests.
week14_inclass2.pyde
network tab

Step 3. In this last step, the network tab includes additional code to receive a response from the server in the form of JSON. It parses that response, and returns it so that you can loop over that data in draw() to render that data on the screen.
week14_inclass3.pyde
network tab
The server code for this is included here: server.py. Remember to put this in a subfolder called cgi-bin within your project folder, and to adjust the permissions to that it is executable (see week 11 for this) and you can run it by running the built-in Python CGI web server (also see week 11).