Search code examples
pythonraspberry-pitornado

Running a Python script in Tornado webserver


My question might be really simple for you, but i'm just starting, so please, help me.

I'm running a home automation script and try to combine it with Tornado webserver.

What is the best way to do it?

Basic Tornado server:

import tornado.ioloop
import tornado.web
import os.path

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

application = tornado.web.Application([
    (r"/", MainHandler)
application = tornado.web.Application([
    (r"/check", MainHandler)
])

if __name__ == "__main__":
    print 'Starting Server'
    print 'Press ctrl+c to close'
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

and a Python script:

import RPi.GPIO as GPIO
import time
import os

motion = 14
relay = 2

GPIO.setmode(GPIO.BCM)
GPIO.setup(motion, GPIO.IN, GPIO.PUD_DOWN)
GPIO.setup(relay, GPIO.OUT)
GPIO.output(relay, GPIO.HIGH)

previous = False
current = False

while True:
    time.sleep(1)
    previous = current
    current = GPIO.input(motion)
    if current != previous:
        new = "HIGH"
        GPIO.output(relay, GPIO.LOW)
        print("GPIO pin %s is %s" % (motion, new))
        os.system("sudo omxplayer ring.mp3 &")
        time.sleep(5)
    else:
        GPIO.output(relay, GPIO.HIGH)
        print("No motions")

Solution

  • If your script were written as a function, you could import it and call it. However, since it contains synchronous code you'd need to use a ThreadPoolExecutor to call it from Tornado.

    Alternately, it's probably better to just launch it as a subprocess. See tornado.process.Subprocess and the standard library's subprocess module.