You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HTML输入框值传入Python函数?含Flask/CGI问题求助

解决方案:用PyScript获取HTML输入并调用Python函数(含CGI/Flask修复方案)

一、最贴合需求的PyScript前端方案

既然你已经用PyScript在HTML中嵌入Python代码,直接在前端处理即可,无需后端CGI/Flask,步骤如下:

完整代码示例

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
    <!-- HTML输入区域 -->
    <input type="text" id="word-input" placeholder="输入单词" value="TESTING">
    <button id="call-func-btn">调用自定义函数</button>
    <div id="result-area"></div>

    <py-script>
        from pyscript import Element

        # 你的自定义函数(替换成你的实际逻辑)
        def anagram(word):
            return f"变位词示例:{''.join(reversed(word))}"

        # 获取DOM元素
        input_box = Element("word-input")
        submit_btn = Element("call-func-btn")
        result_box = Element("result-area")

        # 按钮点击事件处理
        def run_function():
            # 获取输入框的值
            input_word = input_box.value
            if input_word:
                # 调用函数并显示结果
                func_result = anagram(input_word)
                result_box.write(func_result)
            else:
                result_box.write("请输入有效单词")

        # 绑定点击事件
        submit_btn.onclick(run_function)
    </py-script>
</body>
</html>

核心逻辑说明

  • 用PyScript的Element类直接获取HTML元素,通过.value属性读取输入框内容
  • 给按钮绑定点击事件,触发时调用你的自定义函数,最后将结果写入页面指定区域
  • 全程在浏览器前端运行,无需后端服务器配置

二、CGI方案修复

你之前的CGI代码缺少HTTP响应头,导致服务器无法正确解析请求,修改如下:

修复后的Python CGI代码

import cgi, cgitb
cgitb.enable()  # 开启错误追踪,方便调试

form = cgi.FieldStorage()
text = form.getvalue('word')

# 必须先输出HTTP响应头,否则服务器会报错
print("Content-type: text/plain\n")
# 输出获取到的值
print(text if text else "未获取到输入值")

额外注意事项

  • 确保服务器开启CGI支持(如Apache需开启mod_cgi模块)
  • Python脚本需放在服务器指定的CGI目录(如cgi-bin),并设置可执行权限(chmod +x your_script.py)

三、Flask方案修复

你的Flask代码存在3个核心错误:路由定义不完整、获取表单值的键错误、模板路径问题,修复如下:

修复后的Flask后端代码

from flask import Flask, render_template, request

app = Flask(__name__)

# 定义你的自定义函数
def anagram(word):
    return f"变位词示例:{''.join(reversed(word))}"

# 主页路由,直接返回表单页面
@app.route("/")
@app.route("/index")
def index():
    return render_template("py.html")

# 表单提交路由
@app.route("/submit", methods=['POST', 'GET'])
def submit():
    result = None
    error = None
    if request.method == 'POST':
        # 按输入框的name属性获取值,你的输入框name是word,不是submit
        word = request.form.get("word")
        if word:
            result = anagram(word)
        else:
            error = "请输入单词"
    # 将结果/错误传给模板显示
    return render_template("py.html", result=result, error=error)

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

对应的HTML模板(需放在Flask默认的templates目录下,命名为py.html)

<!DOCTYPE html>
<html>
<head>
    <title>Flask表单示例</title>
</head>
<body>
    <form action="/submit" method="post">
        <input name="word" type="text" placeholder="输入单词" value="TESTING">
        <input type="submit" class="file_submit">
    </form>
    <!-- 显示结果或错误 -->
    {% if result %}
        <p style="color:green">{{ result }}</p>
    {% endif %}
    {% if error %}
        <p style="color:red">{{ error }}</p>
    {% endif %}
</body>
</html>

运行说明

  1. 确保项目目录结构为:
    your_project/
    ├── app.py
    └── templates/
        └── py.html
    
  2. 设置环境变量:
    • Windows:set FLASK_APP=app.py
    • Linux/Mac:export FLASK_APP=app.py
  3. 运行:flask run

内容的提问来源于stack exchange,提问作者Kyle Klaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:45:57