Dad? What's for breakfast?
The students union offers the meals from all of it’s canteens via OpenMensa in a machine-readable format for everyone.
We will now go for writing a script that get’s us todays1 meals and prints them for us, nicely formatted.
Getting started
At first, let us analyze what we need to do. The OpenMensa delivers the meals via an URL adhering to the following scheme:
http://openmensa.org/api/v2/canteens/$mensaID/days/$date/meals
The $mensaID of the Alte Mensa is 79. The date has to be formatted as ISO-8601 string (e.g. 2015-12-08
)2.
Using this information, write a function that builds you the link for the meals being served today in the Alte Mensa and return it. Then open the returned link in your web browser. What do you get?3
Working with what we got
So it seems that calling this link get’s us some weird and crappy-formatted JSON file.
Write now a function that gets the content of that file4 and reads the JSON5. Analyze the contents you got.
Details!
Looks like that data is just a list of dicts where every dict represents a separate meal. That makes working with it pretty easy!
So an example meal dict could look like this (with better formatting…):6
So let’s get to work with formatting everything.
Write a function that prints the meals you gathered to the command line, nicely formatted. It should at least display the name of the meal and the price.
You can pimp that by displaying the notes related to the meal.
Data whore
To seal the deal save your formatted text to a *.txt
file.
-
Today sounds like
import time
, doesn’t it? ;) ↩ -
This is equal to the output of
time.strftime("%Y-%m-%d")
. ↩ -
Now that’s some dirty formatted JSON! ↩
-
If you use
urllib.request.urlopen()
, note that this function returns a bytes object when usingread()
that needs to be decoded to UTF-8 usingobject.decode("UTF-8")
↩ -
To load data from a String instead of a file, use
json.loads()
. ↩ -
Remember that there are also dicts and lists inside of that dict! ↩