簡體   English   中英

從Python Flask中的鏈接獲取信息

[英]Getting information from link in Python Flask

我正在嘗試使用樹莓派為arduino創建一個簡單的Web界面。 我想單擊我在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>

當有人單擊鏈接時turn on我希望將字符串發送到action方法,以便可以從那里獲取它。 取而代之的是轉到/on目錄,這並不奇怪。 我到處都看了,找不到解決方法。 這是我第一次使用Flask,而且我對python還是很陌生,所以如果我完全不熟悉,請不要太苛刻。

您可以在執行操作后重定向

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