简体   繁体   English

从Python Flask中的链接获取信息

[英]Getting information from link in Python Flask

I'm trying to make a simple web interface for my arduino using a raspberry pi. 我正在尝试使用树莓派为arduino创建一个简单的Web界面。 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. 我想单击我在html中创建的链接,然后将字符串“ on”发送到python程序,以便它可以告诉arduino打开。 Here's my python code 这是我的python代码

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 这是我的html代码

<!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. 当有人单击链接时turn on我希望将字符串发送到action方法,以便可以从那里获取它。 Instead what it does is go to the /on directory which is not surprising. 取而代之的是转到/on目录,这并不奇怪。 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. 这是我第一次使用Flask,而且我对python还是很陌生,所以如果我完全不熟悉,请不要太苛刻。

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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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