簡體   English   中英

我在一個表單中有多個按鈕/圖像。 如何在 Flask 應用程序中識別被點擊的應用程序?

[英]I have multiple buttons/images in a form. How can I identify, in a Flask application, the one that was clicked?

我有這個 Flask 應用程序,它包含幾個“按鈕”。 我希望能夠對具有不同功能的每個按鈕做出反應。 當前的 HTML(見下文)使用帶有圖像類型的輸入,以便在單擊任何圖像時進行發布操作。

<!doctype html>
<html>
<head>
    <meta http-equiv="refresh" content="60"/>
    <title>Home page</title>
</head>
<body>
    <div>
        <h1 class="title">Automation-Rack Power Controller</h1>
    </div>
    <form method="post">
        <table align="center">
            <tr>
                <td>
                    <div>
                        {% if led_status[0] == '1' %}
                            <img class="led" id="PS1_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS1_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                        <input title="Power Socket 1" name="PS1" type="image" src="/static/TypeH_BlueUpSideDown.png" width="110" height="112">
                    </div>
                </td>
                <td>
                    <div>
                        {% if led_status[2] == '1' %}
                            <img class="led" id="PS3_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS3_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                        <input title="Power Socket 3" name="PS3" type="image" src="/static/TypeH_BlueUpSideDown.png" width="110" height="112">
                    </div>
                </td>
                <td>
                    <div>
                        {% if led_status[4] == '1' %}
                            <img class="led" id="PS5_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS5_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                       <input title="Power Socket 5" name="PS5" type="image" src="/static/TypeH_BlueUpSideDown.png" width="110" height="112">
                    </div>
                </td>
                <td>
                    <div>
                        {% if led_status[6] == '1' %}
                            <img class="led" id="PS7_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS7_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                        <input title="Power Socket 7" name="PS7" type="image" src="/static/TypeH_BlueUpSideDown.png" width="110" height="112">
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div>
                        {% if led_status[1] == '1' %}
                            <img class="led" id="PS2_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS2_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                        <input title="Power Socket 2" name="PS2" type="image" src="/static/TypeH_BluePowerSocket.png" width="110" height="112">
                    </div>
                </td>
                <td>
                    <div>
                        {% if led_status[3] == '1' %}
                            <img class="led" id="PS4_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS4_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                        <input title="Power Socket 4" name="PS4" type="image" src="/static/TypeH_BluePowerSocket.png" width="110" height="112">
                    </div>
                </td>
                <td>
                    <div>
                        {% if led_status[5] == '1' %}
                            <img class="led" id="PS6_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS6_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                        <input title="Power Socket 6" name="PS6" type="image" src="/static/TypeH_BluePowerSocket.png" width="110" height="112">
                    </div>
                </td>
                <td>
                    <div>
                        {% if led_status[7] == '1' %}
                            <img class="led" id="PS8_LED" src="/static/Red_10x10.png" width="10" height="10">
                        {% else %}
                            <img class="led" id="PS8_LED" src="/static/Grey_10x10.png" width="10" height="10">
                        {% endif %}
                        <input title="Power Socket 8" name="PS8" type="image" src="/static/TypeH_BluePowerSocket.png" width="110" height="112">
                    </div>
                </td>
            </tr>
        </table>
    </form>
</body>

在我的 Flask 應用程序中,我能夠識別 POST 請求。 但是,不幸的是我無法識別被點擊的按鈕。 順便說一句,在單擊其中一個按鈕后,我還在屏幕上收到以下錯誤消息:“請求錯誤,瀏覽器(或代理)發送了此服務器無法理解的請求。”

from flask import Flask, render_template, request
import telnetlib
from time import sleep

app = Flask(__name__)


@app.route('/')
def home():
    current_status = Get_Power_State()
    # print(current_status)
    return render_template("home.html", led_status=current_status)


@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        print('Greattttt')
        # print(request.form.get('input'))
        if request.form['PS1']:
            print('Power Socket 1')
        elif request.form['PS2']:
            print('Power Socket 2')
        elif request.form['PS3']:
            print('Power Socket 3')
        elif request.form['image'] == 'PS4':
            print('Power Socket 4')
        elif request.form['image'] == 'PS5':
            print('Power Socket 5')
        elif request.form['image'] == 'PS6':
            print('Power Socket 6')
        elif request.form['image'] == 'PS7':
            print('Power Socket 7')
        elif request.form['image'] == 'PS8':
            print('Power Socket 8')
        else:
            pass  # unknown
    # if request.method == "POST":
    #     Power_On_Off(2, 'off')
    #     print('Power 2 On')

    return '<h1>Clicked one of the buttons</h1>'


def Get_Power_State(Retries=5):
    '''
    Get the Power State of the 8 Power Sockets
    '''
    for attempt in range(Retries):
        try:
            on_off = telnetlib.Telnet('10.0.5.8', 2016)

            on_off.write(b"S00QLE\n")
            sleep(2)
            Power_State = on_off.read_very_eager().decode("utf-8")
            if Power_State == b'':
                raise ValueError("Power Switch didn't respond")
            # Index 3 = Socket 1, Index 4 = Socket 2 ... Index 10 = Socket 8
            Power_State = [Power_State[3], Power_State[4], Power_State[5], Power_State[6],
                           Power_State[7], Power_State[8], Power_State[9], Power_State[10]]

            on_off.close()
            break
        except socket.timeout:
            continue
        except EOFError:
            continue
        except ValueError as e:
            print(e)
            continue

    # print(Power_State)

    return Power_State


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, threaded=True)

我究竟做錯了什么 ? 順便說一句,為了同時為多個客戶端提供服務,我應該使用 Flask 線程選項嗎?

編輯

我嘗試將 替換為包含 ,但在單擊按鈕時甚至沒有像以前那樣收到 POST 請求。 這是打開按鈕的示例

<button title="Power Socket 1" name="PS1" value="Power1" type="button">
    <img src="/static/TypeH_BlueUpSideDown.png" width="110" height="112">
</button>

用於捕獲按鈕值的 FLASK 代碼

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        print('Greattttt')
        # print(request.form.get('input'))
        if request.form['button'] == 'Power1':
            print('Power Socket 1')
        elif request.form['button'] == 'Power2':
            print('Power Socket 2')
        elif request.form['button'] == 'Power3':
            print('Power Socket 3')
        elif request.form['button'] == 'Power4':
            print('Power Socket 4')
        elif request.form['button'] == 'Power5':
            print('Power Socket 5')
        elif request.form['button'] == 'Power6':
            print('Power Socket 6')
        elif request.form['button'] == 'Power7':
            print('Power Socket 7')
        elif request.form['button'] == 'Power8':
            print('Power Socket 8')
        else:
            pass  # unknown

     return '<h1>Clicked one of the buttons</h1>'

您可以使用<button>在HTML代替,因為你可以把一個value是被包括在后的數據。 請參閱https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

不要<button>定義type=button ,因為就像文檔說的那樣,默認類型是submit並且適用於按鈕發送數據:

類型

按鈕的默認行為。 可能的值為:

submit:按鈕將表單數據提交到服務器。 如果未為與 a 關聯的按鈕指定屬性,或者該屬性為空或無效值,則這是默認值。

重置:該按鈕將所有控件重置為其初始值,例如 。 (這種行為往往會惹惱用戶。)

按鈕:按鈕沒有默認行為,默認按下時什么也不做。 它可以讓客戶端腳本偵聽元素的事件,這些事件在事件發生時被觸發。

或者,您可以將圖像輸入指向不同的 URL,覆蓋表單操作,但value方式更好,以及為什么首先進行按鈕輸入。

不,您可能不需要 Flask 的線程,假設您的服務器響應請求足夠快。 這些頁面位於瀏覽器的客戶端,供多個用戶使用,因此即使有一百萬用戶打開頁面通常也沒有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM