gpt4 book ai didi

python - 将数据从 HTML 表单发送到 Flask 中的 Python 脚本

转载 作者:IT老高 更新时间:2023-10-28 20:24:21 24 4
gpt4 key购买 nike

我的 Python 脚本中有以下代码:

def cmd_wui(argv, path_to_tx):
"""Run a web UI."""
from flask import Flask, flash, jsonify, render_template, request
import webbrowser
app = Flask(__name__)


@app.route('/tx/index/')
def index():
"""Load start page where you select your project folder
or load history projects from local DB."""
from txclib import get_version
txc_version = get_version()
prj = project.Project(path_to_tx)

# Let's create a resource list from our config file
res_list = []
prev_proj = ''
for idx, res in enumerate(prj.get_resource_list()):
hostname = prj.get_resource_host(res)
username, password = prj.getset_host_credentials(hostname)
return render_template('init.html', txc_version=txc_version, username=username)

另外,我在 init.html 中有一个 HTML 表单:

<form>
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>

当用户在我的 python 脚本中的变量上单击“spotButton”时,如何从“projectFilepath”传递用户输入?

我是 Python 和 Flask 的新手,如有错误请见谅。

最佳答案

form 标签需要设置一些属性:

  1. action:表单数据在提交时发送到的 URL。使用 url_for 生成它。如果相同的 URL 处理显示表单和处理数据,则可以省略它。
  2. method="post":使用 POST 方法将数据作为表单数据提交。如果没有给出,或者显式设置为 get,则使用 GET 方法在查询字符串 (request.args) 中提交数据。
  3. enctype="multipart/form-data":当表单包含文件输入时,必须设置此编码,否则文件将无法上传,Flask 也看不到它们。

input 标签需要一个name 参数。

添加一个 View 来处理提交的数据,它在 request.form 中与输入的 name 相同的键下。任何文件输入都将在 request.files 中。

@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response

使用 url_for 将表单的 action 设置为该 View 的 URL:

<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>

关于python - 将数据从 HTML 表单发送到 Flask 中的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11556958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com