Skip to main content
 首页 » 编程设计

python之从 Python Flask 中的链接获取信息

2025年05月04日10EasonJim

我正在尝试使用树莓派为我的 arduino 制作一个简单的网络界面。我想单击我在 html 中创建的链接并将字符串“on”发送到 python 程序,以便它可以告诉 arduino 打开。 这是我的 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) 

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

当有人单击链接打开时,我希望将打开的字符串发送到操作方法,以便它可以从那里获取它。相反,它所做的是转到 /on 目录,这并不奇怪。我到处都看过,找不到如何做到这一点。这是我第一次使用 Flask,我对 Python 还很陌生,所以如果我完全不了解,请不要太苛刻。

请您参考如下方法:

您可以在执行操作后直接重定向

from flask import Flask, render_template, request, redirect 
 
@app.route("/<action>") 
def action(action): 
    ... 
    return redirect(url_for('display'))