如何使用Flask在Web服务器中制作两个以上的按钮?

如何解决如何使用Flask在Web服务器中制作两个以上的按钮?

我正在尝试运行Pi Web Server来控制执行器。因此,这是有关我要执行的操作的一些详细信息,我的rpi(3B +)通过XBee与Arduino Nano进行通信,rpi是主服务器,nano是从机,通过我想通过使用以下方法在串行端口上编写的Pi Web服务器按钮(总共6个),然后读取用nano编写的内容,最后控制执行器...

我一直在学习本教程:(https://randomnerdtutorials.com/raspberry-pi-web-server-using-flask-to-control-gpios/),并通过进行一些修改来控制执行器,但是我被困在一个事实,就是我从未使用过Flask框架,而且我是Python的新手。所以我只能使执行器在左右移动。

总而言之,我被困住了,因为我真的不知道如何创建两个以上的按钮,我已经尝试过,但是却收到了我不太理解的错误消息:

Traceback (most recent call last):
  File "app2.py",line 121,in <module>
    @app.route("/<changePin24>/<action24>")
  File "/usr/lib/python2.7/dist-packages/flask/app.py",line 1250,in decorator
    self.add_url_rule(rule,endpoint,f,**options)
  File "/usr/lib/python2.7/dist-packages/flask/app.py",line 66,in wrapper_func
    return f(self,*args,**kwargs)
  File "/usr/lib/python2.7/dist-packages/flask/app.py",line 1221,in add_url_rule
    'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: action
----------------------------------------------------------------------------------------------

我在这里向您展示我的代码:

import RPi.GPIO as GPIO

# ajout du pilotage uart
import serial
import time

port = serial.Serial("/dev/ttyS0",baudrate=9600,timeout=3.0)
# /dev/ttyS0 et non AMA0 !

from flask import Flask,render_template,request

app = Flask(__name__)

GPIO.setmode(GPIO.BCM)

pins4 = {
    4: {'name': 'GPIO 4','state': GPIO.LOW},}

pins24 = {
    24: {'name': 'GPIO 24',}

pins17 = {
    17: {'name': 'GPIO 17',}

pins23 = {
    23: {'name': 'GPIO 23',}

pins22 = {
    22: {'name': 'GPIO 22',}

pins13 = {
    13: {'name': 'GPIO 13',}

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

for pin24 in pins24:
    GPIO.setup(pin24,GPIO.OUT)
    GPIO.output(pin24,GPIO.LOW)

for pin17 in pins17:
    GPIO.setup(pin17,GPIO.OUT)
    GPIO.output(pin17,GPIO.LOW)

for pin23 in pins23:
    GPIO.setup(pin23,GPIO.OUT)
    GPIO.output(pin23,GPIO.LOW)

for pin22 in pins22:
    GPIO.setup(pin22,GPIO.OUT)
    GPIO.output(pin22,GPIO.LOW)

for pin13 in pins13:
    GPIO.setup(pin13,GPIO.OUT)
    GPIO.output(pin13,GPIO.LOW)


@app.route("/")
def main():
    # For each pin,read the pin state and store it in the pins dictionary:
    for pin4 in pins4:
        pins4[pin4]['state'] = GPIO.input(pin4)

    for pin24 in pins24:
        pins24[pin24]['state'] = GPIO.input(pin24)

    for pin17 in pins17:
        pins17[pin17]['state'] = GPIO.input(pin17)

    for pin23 in pins23:
        pins23[pin23]['state'] = GPIO.input(pin23)

    for pin22 in pins22:
        pins22[pin22]['state'] = GPIO.input(pin22)

    for pin13 in pins13:
        pins13[pin13]['state'] = GPIO.input(pin13)

    # Put the pin dictionary into the template data dictionary:
    templateData = {
    'pins4': pins4,'pins24': pins24,'pins17': pins17,'pins23': pins23,'pins22': pins22,'pins13': pins13,}
# Pass the template data into the template main.html and return it to the user
    return render_template('main.html',**templateData)

# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/<changePin4>/<action4>")
def action(changePin4,action4):
# Convert the pin from the URL into an integer:
    changePin4 = int(changePin4)
#----------------------------------------------------------------------------------------------------
@app.route("/<changePin24>/<action24>")
def action(changePin24,action24):
# Convert the pin from the URL into an integer:
    changePin24 = int(changePin24)
#----------------------------------------------------------------------------------------------------
@app.route("/<changePin17>/<action17>")
def action(changePin17,action17):
# Convert the pin from the URL into an integer:
    changePin17 = int(changePin17)
#----------------------------------------------------------------------------------------------------
@app.route("/<changePin23>/<action23>")
def action(changePin23,action23):
# Convert the pin from the URL into an integer:
    changePin23 = int(changePin23)
#----------------------------------------------------------------------------------------------------
@app.route("/<changePin22>/<action22>")
def action(changePin22,action22):
# Convert the pin from the URL into an integer:
    changePin22 = int(changePin22)
#----------------------------------------------------------------------------------------------------
# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/<changePin13>/<action13>")
def action(changePin13,action13):
# Convert the pin from the URL into an integer:
    changePin13 = int(changePin13)
#----------------------------------------------------------------------------------------------------
# Get the device name for the pin being changed:
    deviceName4 = pins4[changePin4]['name']
    deviceName24 = pins24[changePin24]['name']
    deviceName17 = pins17[changePin17]['name']
    deviceName23 = pins23[changePin23]['name']
    deviceName22 = pins22[changePin22]['name']
    deviceName13 = pins13[changePin13]['name']
# --------------------------------------------ACTIONNEUR HORIZONTAL---------------------------------
# Change the direction of the Actuator plugged on PWMA
# If the action part of the URL is "on," execute the code indented below:
    if action4 == "on":
    # Set the pin high:
        GPIO.output(4,GPIO.HIGH)
    # Save the status message to be passed into the template:
        message = "Turned " + deviceName4 + " on."
        port.write("HD")
    # horizontal right

    if action4 == "off":
        GPIO.output(4,GPIO.LOW)
        message = "Turned " + deviceName4 + " off."
        port.write("SH")
    # stop
# ---------------------------------------------------------------------------------------------------
    if action24 == "on":
    # Set the pin high:
        GPIO.output(24,GPIO.HIGH)
    # Save the status message to be passed into the template:
        message = "Turned " + deviceName24 + " on."
        port.write("HG")
    # horizontal left

    if action24 == "off":
        GPIO.output(24,GPIO.LOW)
        message = "Turned " + deviceName24 + " off."
        port.write("SH")
        #stop
#----------------------------------------------ACTIONNEUR VERTICAL-----------------------------------------------
#Change the direction of the actuator plugged on PWMB
    if action17 == "on":
    # Set the pin high:
        GPIO.output(17,GPIO.HIGH)
    # Save the status message to be passed into the template:
        message = "Turned " + deviceName17 + " on."
        port.write("VH")
    #vertical up

    if action17 == "off":
        GPIO.output(17,GPIO.LOW)
        message = "Turned " + deviceName17 + " off."
        port.write("SV")
    #stop
#---------------------------------------------------------------------------------------------------
#Change the direction of the actuator plugged on PWMB
    if action23 == "on":
      # Set the pin high:
        GPIO.output(23,GPIO.HIGH)
 # Save the status message to be passed into the template:
        message = "Turned " + deviceName23 + " on."
        port.write("VB")
         #vertical down

    if action23 == "off":
        GPIO.output(23,GPIO.LOW)
        message = "Turned " + deviceName23 + " off."
        port.write("SV")
        #stop
#---------------------------------------------WHERE WE SET MOTOR'S SPEED--------------------------------------------
# Change the speed of PWM ===> Pulse Width Modulation
    if action22 == "on":
        # Set the pin high:
        GPIO.output(22,GPIO.HIGH)
        # Save the status message to be passed into the template:
        message = "Turned " + deviceName22 + " on."
        port.write("PWMmoyen")
        # Middle speed motor

    if action22 == "off":
        GPIO.output(22,GPIO.LOW)
        message = "Turned " + deviceName22 + " off."
        port.write("SPWM")
        # stop
# ---------------------------------------------------------------------------------------------------
        # Change the speed of PWM ===> Pulse Width Modulation
    if action13 == "on":
            # Set the pin high:
        GPIO.output(13,GPIO.HIGH)
            # Save the status message to be passed into the template:
        message = "Turned " + deviceName13 + " on."
        port.write("PWMmax")
            # Middle speed motor

    if action13 == "off":
        GPIO.output(13,GPIO.LOW)
        message = "Turned " + deviceName13 + " off."
        port.write("SPWM")
        # stop
# ---------------------------------------------------------------------------------------------------

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

    for pin24 in pins24:
        pins24[pin24]['state'] = GPIO.input(pin24)

    for pin17 in pins17:
        pins17[pin17]['state'] = GPIO.input(pin17)

    for pin23 in pins23:
        pins23[pin23]['state'] = GPIO.input(pin23)

    for pin22 in pins22:
        pins22[pin22]['state'] = GPIO.input(pin22)

    for pin13 in pins13:
        pins13[pin13]['state'] = GPIO.input(pin13)

    #put pin's state in data dictionary:
    templateData = {
        'pins4': pins4,}

    return render_template('main.html',**templateData)

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

解决方法

错误是因为所有功能使用相同的名称:def action(changePinxx,actionxx):

每个视图的功能必须具有不同的名称。接下来,我们可以讨论不使用所有不同的功能。

这些网址:

/foo/bar

/hey/there

没有办法知道去哪里。将它们全部放在一个函数中:

@app.route("/<number>/<changePin>/<action>")
def action(number,changePin,action):
    changePin = int(changePin)
    # now do something with changePin #number

然后,处理您的字典:

pins = {
    4: {'name': 'GPIO 4','state': GPIO.LOW},24: {'name': 'GPIO 24',etc.
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-