2014-04-15 25 views
2

我正在嘗試使用覆盆子pi爲我的arduino製作一個簡單的Web界面。我想單擊一個我在html中創建的鏈接,並將字符串「on」發送到python程序,以便它可以告訴arduino打開。 這裏是我的Python代碼從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 。相反,它所做的是去/on目錄,這並不奇怪。我到處尋找,無法找到如何做到這一點。這是我第一次使用Flask,我對python相當陌生,所以如果完全關閉,請不要太苛刻。

+1

實際上後,您可以只把它重定向將路由給你的'/ on'這是目前不存在,因爲你有兩條路'/'和'/ ' 。你可以將'/ action'路由改爲'/ on',但是如果你想傳遞一個字符串,我建議你使用'form'然後提交它。 –

+0

你還必須將第一個路由改爲'/ ,methods = [「GET」,「POST」]' –

+0

是不是有辦法從鏈接中取出字符串併發送它? – user2197126

回答

1

你採取行動

from flask import Flask, render_template, request, redirect 

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

好的,你解決了我的問題。然而,'return redirect(url_for('display'))'不起作用,所以我不得不從顯示方法重新創建代碼。我如何使用'url_for'來顯示顯示方法中的html? – user2197126

+0

url_for將重定向到指定的方法。所以在這種情況下,它會重定向到url_for - > display()。該URL位於路由裝飾器中,在本例中爲「/」。確保你添加了'from flask import Flask,render_template,request,redirect'部分('redirect'是extra) –