Calling Functions in Flask

2.2k Views Asked by At

Apologies in advance as this is probably the most basic question to be found here but I'm the greenest of newbies and cannot get my head around how to call a function in flask so it runs when I land on the URL.

My purpose is to try and get a python script to run when a GET request is made to the URL from WebCore (for those who don't know it's a program that allows you to code smart home functionality for SmartThings) or when I simply land at the URL. I will then tie this to a virtual switch which will start the code which controls a motor in a cat feeder so I can feed my cat remotely/by voice.

All very frivolous stuff but trying to learn some basics here, can anyone help?

As it stands I have two files, both in a root directory named 'CatFeeder'

catfeeder.py

from flask import Flask
from feed import start

app = Flask(__name__)

@app.route('/')
def feed()
    return feed.start

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000', debug=True)

feed.py

import time
import RPi.GPIO as GPIO

def start():
    # Next we setup the pins for use!
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    Motor1Forward = 17
    Motor1Backwards = 18

    GPIO.setup(Motor1Forward,GPIO.OUT)
    GPIO.setup(Motor1Backwards,GPIO.OUT)

    print('Feeding Lola')

    # Makes the motor spin forward for x seconds 
    # James Well Beloved - 11 seconds = 28g food (RDA Portion = 52g/4kg cat or 61g/5kg cat)
    # XXXX - X seconds - Xg food

    GPIO.output(Motor1Forward, True)
    GPIO.output(Motor1Backwards, False)
    time.sleep(11)

    print('Lola Fed!')

    GPIO.output(Motor1Forward, False)
    GPIO.output(Motor1Backwards, False)

    GPIO.cleanup()

    quit()

When I set export FLASK_APP=catfeeder.py and then flask run the service runs but nothing happens when I land on the page. I assume there is something wrong in the way I am calling things.

I guess it would be easiest if I just integrated the code from feed.py into catfeeder.py but I wasn't sure what the syntax would be for this and it felt like a messy way to go about it.

Thanks in advance!

1

There are 1 best solutions below

2
On

you've imported the function but didn't actually invoke it as you missed adding your brackets (), try return start()

In case you meant to return a function object and not invoke the function, you should return it by typing return start