首页 > 解决方案 > 如何在 Flask 的一页中包含多个输入表单?

问题描述

不久前,我用烧瓶制作了一个简单的网络应用程序,只有一个输入表单。我现在正在开发另一个具有 8 个输入表单的应用程序,但我无法弄清楚如何让它与多个输入表单一起工作。似乎只能有一个 url 端点,并且每个函数都需要与端点具有相同的名称。我尝试编写一个接收所有 8 个输入的函数,但每个表单都被命名,并且一次只能收集 ​​1 个表单。简单来说,我有一个包含 8 个用户输入表单的应用程序,我正在尝试收集这些输入并将它们存储在 MySQL 数据库中。

from flask import Flask, request, jsonify, render_template
import mysql.connector
from getpass import getpass
from mysql.connector import connect
password = input('Enter password: ')
connection = connect(host='localhost', user='root', password=password, database='leads')
cursor = connection.cursor()
connection2 = connect(host='localhost', user='root', password=password, database='fox_data_consulting')
cursor2 = connection2.cursor()

app = Flask(__name__)
#name, customer, domain = processUserInput(name, customer, domain)

@app.route('/')
def home():
    return render_template('index.html')

#try using another function with the same name
@app.route('/store', methods=['POST'])
def store(): #name would be more practical but it's unable to work unless it matches the route
    name = request.form['name'].lower()
    cursor.execute('''INSERT INTO test (col1) VALUES ('{}');'''.format(name))
    connection.commit()
    '''
    #werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'landingPage'
    landingPage = request.form['landingPage'].lower()
    cursor.execute("INSERT INTO test (col2) VALUES ('{}');".format(landingPage))
    connection.commit()'''
    return name

#second function under the same route
'''def landingPage():
    #werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.KeyError: 'name'
    landingPage = request.form['landingPage']
    cursor.execute("INSERT INTO test (col2) VALUES ('{}');".format(landingPage))
    connection.commit()
    return landingPage'''

if __name__ == "__main__":
    app.run(debug=True, threaded=True)```

The docstrings is code that I've tried but didn't work, Thank you in advance.

标签: flask

解决方案


原来我可以在应用程序中有多个路线,这已经解决了


推荐阅读