A Python + Bottle web server example application

I’m working on an application/system where I have an FM radio chip in a Raspberry Pi, and I control the radio chip with a web service. The web service is written in Python, and is powered by the Python “Bottle” web server.

Here’s the Python/Bottle source code for my radio web application:

from bottle import route, run, template

# the radio chip is an si4703; this is a python library to control it
import si4703
fm = si4703.si4703()

isOn = False

@route('/')
def index():
    return 'hello, world'

@route('/tune/<station>')
def tune(station = '104.3'):
    global isOn
    if isOn == False:
        fm.init()
        isOn = True
    fm.tune(station)
    return 'ack'

@route('/turn_off')
def turn_off():
    global isOn
    isOn = False
    fm.turn_off()
    return 'ack'

@route('/set_volume/<volume>')
def set_volume(volume = '10'):
    f,.volume(volume)
    return 'ack'

run(host='localhost', port=5151)

If you’re familiar with Scala, this code looks like Scalatra (or Sinatra in Ruby). Libraries like this make creating small web applications very simple/easy/fast. I may write more about this in the future, but for today I just wanted to share this code in case someone needs a Python/Bottle example to get started.

Oops, I guess it would help to mention that I start the server like this on the Raspberry Pi (RPI):

$ sudo python server.py

This script is named server.py, and the sudo part is needed because the si4703 library interacts with the RPI GPIO (hardware) ports.