在Flathon中使用Flask app运行连续的while循环

时间:2015-08-17 07:56:44

标签: python loops while-loop flask

我正在使用python在raspberry pi中编写代码,我希望用户通过网页输入设定温度和风扇模式我使用flask来获取并且值成功返回但我也想要运行无限循环以及烧瓶应用程序,它将设置温度与来自传感器的当前温度进行比较..如何在不中断烧瓶应用程序的情况下实现此目的?

from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
import time
temp = ""
t = ""
fan_High = 0
fan_Med = 0
fan_Low =0
fanspeed = ""


app = Flask(__name__)


@app.route('/form', methods=['POST'])
def aziz():
    global temp ,fanspeed
    fanspeedlocal = ''
    if request.form['settemp'] != "":
        temp = request.form['settemp']
        templocal = temp
    else:
        templocal = temp


    if request.form['speed'] == "null":
        fanspeedlocal = fanspeed
    else:
        if request.form['speed'] == "High":
            fan_Med = False
            fan_Low = False
            fan_High = True
            fanspeed = "High"
            fanspeedlocal = fanspeed
        elif request.form['speed'] == "Med":
            fan_High = False
            fan_Low = False
            fan_Med = True
            fanspeed = "Medium"
            fanspeedlocal = fanspeed
        elif request.form['speed'] == "Low":
            fan_High = False
            fan_Med = False
            fan_Low = True
            fanspeed = "Low"
            fanspeedlocal = fanspeed
    print 'Settemp = %s' %temp
    print 'fanspeed = %s' %fanspeed
    return render_template('Output.html',temp=templocal,currtemp=strct,time=t,fanspeed=fanspeedlocal




@app.route('/')
def start():
    global t , fanspeed
    t = time.strftime("%H:%M:%S")    
    return render_template('Start.html',temp=temp,currtemp=strct,time=t,fanspeed=fanspeed)




if __name__ == '__main__':
    app.debug = False
    app.run(host = '192.168.1.101')


var = 1
while var == 1:
    inttemp = int(temp)
    if currtemp >= inttemp:
            #set GPIO to high
    else:
            #set GPIO to low

    if fanspeed == 'High':
            #set GPIO to high
    elif fanspeed == 'Med':
            #set GPIO to high
    elif fanspeed == 'LOW':
            #set GPIO to high
    time.sleep(10)

2 个答案:

答案 0 :(得分:1)

我会用cron。你可以使用一个看起来像这样的简单脚本:

#!/usr/bin/python3 
# or python, if that's your thing

import requests

def get_sensor_data():
    '''Presumably you know what actually goes here.'''
    return {'temperature': 5, 'fan speed': 'no, three, sir'}

requests.post('http://example.com/update?api_key=12345', data=get_sensor_data())

然后只需将cron设置为每60秒或更短时间运行一次。现在,您的Flask应用程序只会从您的脚本获取更新数据的请求,同时页面更新。

或者,您可以设置一个Flask @app.before_request decorator,它只会请求必要的数据并将其附加到特殊的g对象。

如果快速(<250ms)读取数据,我可能会做后者。如果它需要超过250毫秒,那么我可能会让cron这样做。

答案 1 :(得分:0)

我想,你只需在:

中输入while命令
sorted(('{:08b}'.format(i) for i in xrange(256)), key=lambda x: x.count('1'))

或在某个你喜欢的地方