Flask Server Test on Raspberry Pi for control LED

Environment

  • Raspberry Pi 3B+
  • Raspbian GNU/Linux 9.4
  • Python 3
  • Flask 1.0.2

Setup Flask

$ pip3 install Flask

Code

$ vim led_flask.py
#!/usr/bin/python3


from flask import Flask
import json
import RPi.GPIO as GPIO


GPIO.setwarnings(False)    # Ignore warning for now
GPIO.setmode(GPIO.BOARD)   # Use physical pin numbering
GPIO.setup(13, GPIO.OUT, initial=GPIO.LOW)

app = Flask(__name__)

@app.route('/')
def hello():
    name = "Top Page"
    return name

@app.route('/api/led/', methods=['PUT'])
def led(key):
    if key == "1":
        GPIO.output(13, GPIO.HIGH)
        return "LED ON \n"
    elif key == "0":
        GPIO.output(13, GPIO.LOW)
        return "LED OFF \n"
    else:
        return "Command Not Found \n"

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

Result

$ sudo python3 led_flask.py
 * Serving Flask app "led_flask" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5004/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 337-794-775
$ curl -X PUT http://x.x.x.x:5004/api/led/1
LED ON 
$ curl -X PUT http://x.x.x.x:5004/api/led/0
LED OFF 
$ curl -X PUT http://x.x.x.x:5004/api/led/2
Command Not Found