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

如何将已编写的Python代码添加至HTML项目以实现功能扩展?

解决Python代码嵌入HTML的几种可行方案

1. 用Python后端框架实现前后端交互

这是生产环境最常用的方案,把Python逻辑放在后端作为接口服务,HTML前端通过HTTP请求调用后端功能。以Flask为例:

  • 后端Python代码(app.py):
from flask import Flask, jsonify, request

app = Flask(__name__)

# 你的自定义功能逻辑
def custom_function(data):
    return f"处理后的结果:{data.upper()}"

# 定义接口路由
@app.route('/api/process', methods=['POST'])
def process_data():
    input_data = request.json.get('input')
    result = custom_function(input_data)
    return jsonify({'result': result})

if __name__ == '__main__':
    app.run(debug=True)
  • 前端HTML代码:
<!DOCTYPE html>
<html>
<body>
    <input type="text" id="inputText" placeholder="输入内容">
    <button onclick="sendRequest()">提交</button>
    <div id="result"></div>

    <script>
        function sendRequest() {
            const input = document.getElementById('inputText').value;
            fetch('/api/process', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({input: input})
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').textContent = data.result;
            });
        }
    </script>
</body>
</html>

启动Flask服务后,访问页面即可调用Python自定义功能。

2. 使用模板引擎嵌入Python逻辑

如果需要在HTML中直接使用Python变量或简单逻辑(循环、条件判断等),可以用模板引擎,比如Flask默认的Jinja2:

  • 后端Python代码(app.py):
from flask import Flask, render_template

app = Flask(__name__)

def custom_function(text):
    return text.capitalize()

@app.route('/')
def index():
    # 传递数据到模板
    user_info = {'name': '测试用户', 'projects': ['HTML项目', 'Python功能']}
    processed_text = custom_function('hello world')
    return render_template('index.html', user=user_info, text=processed_text)
  • 模板HTML(templates/index.html):
<!DOCTYPE html>
<html>
<body>
    <h1>欢迎 {{ user.name }}</h1>
    <p>处理后的文本:{{ text }}</p>
    <h3>我的项目:</h3>
    <ul>
        {% for item in user.projects %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

模板中用{{ 变量名 }}输出Python数据,{% 逻辑语句 %}编写循环、条件等逻辑。

3. 用PyScript直接在HTML中运行Python

如果不想搭建后端服务器,PyScript可以让你直接在HTML里写Python代码,浏览器会在前端转译执行(适合轻量功能):

<!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>
    <input type="text" id="input" placeholder="输入内容">
    <button id="btn">点击处理</button>
    <p id="output"></p>

    <py-script>
        from pyscript import Element

        def custom_function(data):
            return f"处理结果:{data.lower()}"

        def handle_click():
            input_val = Element('input').value
            result = custom_function(input_val)
            Element('output').write(result)

        # 绑定按钮点击事件
        Element('btn').element.onclick = handle_click
    </py-script>
</body>
</html>

4. 传统CGI方式(适合小型测试项目)

配置服务器(如Apache、Nginx)支持CGI,将Python脚本作为CGI程序运行:

  • Python CGI脚本(cgi-bin/process.py):
#!/usr/bin/env python3
import cgi

# 获取表单输入
form = cgi.FieldStorage()
input_data = form.getvalue('input', '')

# 自定义处理逻辑
def custom_function(data):
    return f"CGI处理结果:{data * 2}"

result = custom_function(input_data)

# 返回HTML响应
print("Content-Type: text/html")
print()
print(f"<html><body><p>{result}</p></body></html>")
  • HTML代码:
<!DOCTYPE html>
<html>
<body>
    <form action="/cgi-bin/process.py" method="post">
        <input type="text" name="input">
        <button type="submit">提交</button>
    </form>
</body>
</html>

需确保服务器配置了CGI目录,且脚本具备执行权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:40:55