简体   繁体   中英

Getting information from link in Python Flask

I'm trying to make a simple web interface for my arduino using a raspberry pi. I want to click a link that i create in html and send the string "on" to the python program so it can tell the arduino to turn on. Here's my python code

import serial
from flask import Flask, render_template, request
import datetime
app = Flask(__name__)
ser = serial.Serial('/dev/ttyACM0', 9600)

@app.route("/<action>")
def action(action):
    print action 
    #command = ""
    #while command != "done":
    #       command = raw_input("what do you want? ")
    if action == "on":
            ser.write('1')
    elif action == "off":
            ser.write('0')
    return render_template('index.html', **templateData)

@app.route("/")
def display():
    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")
    templateData = {
            'title' : 'arduino',
            'time' : timeString
    }
    return render_template('index.html', **templateData)

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

and here's my html code

<!DOCTYPE html>
    <head>
            <title>{{title}}</title>
    </head>
    <body>
            <p>The time at server is {{time}}</p>
            <p>
                The LED is currently off (<a href="/on">turn on</a>)
            </p>
    <body>
</html>

When someone clicks the link turn on I want the string on to be sent to the action method so that it can take it from there. Instead what it does is go to the /on directory which is not surprising. I've looked everywhere and can't find how to do this. This is my first time ever using Flask and I'm fairly new to python so please don't be too harsh if I'm completely off.

You could just redirect after you take the action

from flask import Flask, render_template, request, redirect

@app.route("/<action>")
def action(action):
    ...
    return redirect(url_for('display'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM