Day 15 of the Anvil Advent Calendar

Build a web app every day until Christmas, with nothing but Python!

Everything’s cooler from the command line.

For some people (and I’m among that number), nothing is truly computer-controlled until you can drive it from the command line. So today, we’ve taken our Raspberry-Pi-powered Christmas tree, and built a command line script to drive it.

It’s nice and terse: treectl on.

This script uses Anvil’s client uplink to connect to our Anvil app as untrusted code – just like the Python code in your web browser! (Yes, Python in the browser! It’s our thing. Hit our homepage for more.)

Giving out the client uplink key is less risky than the server uplink key. The server uplink can handle requests from your app, by defining @anvil.server.callable functions, and it can access the database. The client uplink is more restricted - it has exactly the same permissions as a web browser. This is perfect for a command-line script we want to distribute to our users.

We open the Uplink dialog, and find our app’s Client Uplink key:

And then we make a script that calls anvil.server.connect() using that key:

#!/usr/bin/env python

import sys
import anvil.server

if len(sys.argv) != 2 or sys.argv[1] not in {'on', 'off'}:
    print('Usage: "treectl on" or "treectl off"')
    sys.exit(1)

anvil.server.connect("RKH2FGALSM756FCZZJJYIWAD-JXAGUVP6U7NH5ZI3-CLIENT")

if sys.argv[1] == "on":
    anvil.server.call("lights_on")
else:
    anvil.server.call("lights_off")

Optional: If you’re on a Unix system (Mac or Linux), you can make it executable by anyone logged into your computer:

$ sudo cp treectl.py /usr/local/bin/treectl
$ sudo chmod +x /usr/local/bin/treectl

Now send that script to your favourite terminal fiend, and let them toggle your Christmas lights with a touch of the keyboard – from anywhere in the world!


Give the Gift of Python

Share this post: