从Flas中的不同应用程序路由调用另一个应用程序路由

2024-06-02 08:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个webapp烧瓶,运行它来处理要显示的数据图表和一些gpio控件。所有的功能,比如从sqlite数据库显示数据,从按钮gpio控制全部工作。在

下面的代码是我的webapp烧瓶,其中包含许多应用程序路由。我的主要问题是:

  1. 当我按下开关继电器的按钮时,不知何故我的数据不会自动加载。所以我必须手动点击刷新按钮
  2. 当我输入特定的数字作为输入,并期望数据显示为特定数字的范围时,如果我在点击gpio控制按钮进行中继之前就这样做了,它将起作用。但我点击了gpio控制按钮,我无法做到这一点,网页上说“方法不允许”。在

因此,在我看来,如果我们在这个路由中添加一些代码来调用索引路由(“/”),它可能会起作用:@应用程序路径("//") . 但不幸的是,我对python和flask没有太多的经验,在php web服务器上也许可以工作,但不知道使用这种语言。也许你能给我一些线索?在

我的目标是,这个页面将能够处理控制gpio(中继)和用matplotlib图表显示数据的两个动作

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
import RPi.GPIO as GPIO
#import water

from flask import Flask, render_template, send_file, make_response, request
app = Flask(__name__)

import sqlite3


#GPIO NEEDS############################################################
GPIO.setmode(GPIO.BCM)
# Create a dictionary called pins to store the pin number, name, and pin state:
pins = {
   13 : {'name' : 'Waterpump 1', 'state' : GPIO.LOW},
   19 : {'name' : 'Growlight 2', 'state' : GPIO.LOW}
   }

# Set each pin as an output and make it low:
for pin in pins:
   GPIO.setup(pin, GPIO.OUT)
   GPIO.output(pin, GPIO.LOW)

conn=sqlite3.connect('../sensorsData.db')
curs=conn.cursor()


# Retrieve LAST data from database
def getLastData():
    for row in curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT 1"):
        time = str(row[0])
        temp = row[1]
        hum = row[2]
    #conn.close()
    return time, temp, hum


def getHistData (numSamples):
    curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT "+str(numSamples))
    data = curs.fetchall()
    dates = []
    temps = []
    hums = []
    for row in reversed(data):
        dates.append(row[0])
        temps.append(row[1])
        hums.append(row[2])
    return dates, temps, hums

def maxRowsTable():
    for row in curs.execute("select COUNT(temp) from  DHT_data"):
        maxNumberRows=row[0]
    return maxNumberRows

#initialize global variables
global numSamples
numSamples = maxRowsTable()
if (numSamples > 101):
    numSamples = 100


# main route 
@app.route("/")
def index():


    time, temp, hum = getLastData()
    templateData = {
      'time'        : time,
      'temp'        : temp,
      'hum'         : hum,
      'numSamples'  : numSamples,
      'pins' : pins
#      'text' : text
    }
    return render_template('index.html', **templateData)

#method for gpio########################################################
def main():
   # For each pin, read the pin state and store it in the pins dictionary:
   for pin in pins:
      pins[pin]['state'] = GPIO.input(pin)
   # Put the pin dictionary into the template data dictionary:
   templateData = {
      'pins' : pins
      }
   # Pass the template data into the template main.html and return it to the user
   return render_template('index.html', **templateData)



@app.route('/', methods=['POST'])
def my_form_post():
    global numSamples 
    numSamples = int (request.form['numSamples'])
    numMaxSamples = maxRowsTable()
    if (numSamples > numMaxSamples):
        numSamples = (numMaxSamples-1)

    time, temp, hum = getLastData()

    templateData = {
      'time'        : time,
      'temp'        : temp,
      'hum'         : hum,
      'numSamples'  : numSamples
    }
    return render_template('index.html', **templateData)


@app.route('/plot/temp')
def plot_temp():
    times, temps, hums = getHistData(numSamples)
    ys = temps
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    axis.set_title("Temperature [C]")
    axis.set_xlabel("Samples")
    axis.grid(True)
    xs = range(numSamples)
    axis.plot(xs, ys)
    canvas = FigureCanvas(fig)
    output = io.BytesIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response

@app.route('/plot/hum')
def plot_hum():
    times, temps, hums = getHistData(numSamples)
    ys = hums
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    axis.set_title("Humidity [%]")
    axis.set_xlabel("Samples")
    axis.grid(True)
    xs = range(numSamples)
    axis.plot(xs, ys)
    canvas = FigureCanvas(fig)
    output = io.BytesIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response


###APPROUTEGPIO##########################################################
@app.route("/<changePin>/<action>")
def action(changePin, action):
   # Convert the pin from the URL into an integer:
   changePin = int(changePin)
   # Get the device name for the pin being changed:
   deviceName = pins[changePin]['name']
   # If the action part of the URL is "on," execute the code indented below:
   if action == "on":
      # Set the pin high:
      GPIO.output(changePin, GPIO.HIGH)
      # Save the status message to be passed into the template:
      message = "Turned " + deviceName + " on."
   if action == "off":
      GPIO.output(changePin, GPIO.LOW)
      message = "Turned " + deviceName + " off."

   # For each pin, read the pin state and store it in the pins dictionary:
   for pin in pins:
      pins[pin]['state'] = GPIO.input(pin)

   # Along with the pin dictionary, put the message into the template data dictionary:
   templateData = {
      'pins' : pins
   }

   return render_template('index.html', **templateData)
##approutesoil################################################################
#@app.route("/sensor")
#def action():
#    status = water.get_status()
#    message = ""
#    if (status == 1):
#        message = "Water me please!"
#    else:
#        message = "I'm a happy plant"
#
#    templateData = template(text = message)
#    return render_template('index.html', **templateData)



if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=False)

Tags: theoutputgpioreturnresponsedefpintemplate