Fornetto publishes to WordPress with Raspberry Pi and Python

Finally I took the time to clean up the Python code that publishes to images from the modified microwave toy to a WordPress site. I’m lying: the code is not clean at all but it serves its purpose… ship it!

In the process I learned a few things about WordPress REST API, Python and the Raspberry Pi. All fun. Python is basically the default language for Raspberry Pi. There are numerous modules to access all the hardware functions of the board and countless examples, tutorials, blog posts, wiki pages, meetups all about Python. The REST API Handbook is the main resource I used.  Many tutorials online were written when the WP APIs were a separate plugin and they seem outdated. The handbook seems to be written with developers working within WordPress, with all examples provided in PHP and Javascript. I ended up writing a brief tutorial on how to create a post with images to WordPress using Python.

There are lots of photobooth applications targeting Raspberry Pis out there. I ended up forking drumminhands_photobooth which seemed polished enough. It’s originally designed to snap 4 pictures at the press of a button, blink a LED and show previews of the pictures on a screen, then create an animated GIF from the snapped poses and publish them to tumblr. Alternatively, publishes 4 independent JPEGs, based on a configuration option.

One cool thing about tumblr APIs is that they have a Python library dealing with authentication and the basic publishing operations. WordPress REST API don’t have anything like that (yet). Even authentication from a Python app requires an external plugin, which is not ideal.

The core of the photobooth app is the function publishing to WordPress:

def wp_make_post(gif, wp_title, wp_content):
        wpupload = + "/media", headers=wpheaders, files=gif)
	print "Your image is on " + json.loads(wpupload.content)['link']
	# get the post ID from WP
	wpimg = json.loads(wpupload.content)['id']
	print wpimg
	# prepare the post content in json
	wppost = {'categories':'3', \
                  'title':wp_title, \
                  'content':wp_content, \
                  'format':'image', \
                  'featured_media':wpimg, \
                  'author':'1', \
	print wppost
	# post the json to WP
	wpdopost = + "/posts", headers=wpheaders, json=wppost)
displayStatus("Your image is on " + json.loads(wpdopost.content)['link'], 14)

Now every time someone pushes the Start button on the toy microwave, its light blinks and the screen shows instructions while snapping pictures and uploading them.

On the WordPress side, I picked Morphology Lite because of how the home page can be turned into a mosaic of images from the Featured image of the post. That’s it! I’ll update this post once I have enough images from an event.