使用deepseek生成一个网页的简单架构

python代码如下:

from flask import Flask, render_template, jsonify

app = Flask(name)

#定义要调用的Python函数
def cac_sum():
“”“示例计算函数”""
str_print = ‘现在打印这个了,哈哈哈哈哈哈’
return {“result”: str_print} # 返回计算结果

@app.route(’/’)
def index():
return render_template(‘index.html’)

@app.route(’/calculate’, methods=[‘POST’])
def calculate():
return jsonify(cac_sum())

if name == ‘main’:
app.run(debug=True)

分界线=========

html 代码

html

Python函数调用示例

点击按钮调用Python函数

点击计算

原版

以下是实现该功能的完整步骤和代码示例:

整体方案

使用Python Flask框架搭建后端,HTML+JavaScript作为前端,实现前后端交互。


第一步:安装Flask(需Python环境)

pip install flask

第二步:项目结构

your_project/
├── app.py          # 后端代码
├── templates/
│   └── index.html  # 前端页面

第三步:后端代码(app.py)

from flask import Flask, render_template, jsonify

app = Flask(__name__)

# 定义要调用的Python函数
def cac_sum():
    """示例计算函数"""
    return {"result": 3 + 5}  # 返回计算结果

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

@app.route('/calculate', methods=['POST'])
def calculate():
    return jsonify(cac_sum())

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

第四步:前端页面(templates/index.html)

DOCTYPE html>
<html>
<head>
    <title>Python函数调用示例title>
    <script>
        function callPythonFunction() {
            fetch('/calculate', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').innerHTML = '计算结果:' + data.result;
            })
            .catch(error => console.error('Error:', error));
        }
    script>
head>
<body>
    <h1>点击按钮调用Python函数h1>
    <button onclick="callPythonFunction()">点击计算button>
    <div id="result">div>
body>
html>

第五步:运行与测试

  1. 启动Flask服务
python app.py
  1. 浏览器访问
http://localhost:5000
  1. 点击按钮即可看到计算结果

效果说明

  • 点击按钮后会调用后端cac_sum()函数
  • 后台计算结果会通过JSON格式返回
  • 前端使用fetch API获取结果并显示
  • 每次点击都会重新计算结果

扩展建议

  1. 要修改计算逻辑,直接修改cac_sum()函数内容
  2. 可添加加载动画(在fetch时显示加载中状态)
  3. 可添加错误处理机制
  4. 生产环境建议关闭debug模式
  5. 可添加参数传递功能(例如让用户输入计算数值)

这个方案实现了基本的网页调用Python函数功能,可以根据实际需求进一步扩展功能。

服务器访问方式

要实现通过公网IP让所有人访问你的Flask网页应用,需要以下步骤:


第一步:基础配置

1. 修改Flask监听地址

在启动应用时添加host=0.0.0.0参数:

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=False)  # 关闭调试模式
2. 开放服务器防火墙端口
  • Linux(示例为Ubuntu):
    sudo ufw allow 5000/tcp
    sudo ufw reload
    
  • Windows
    控制面板 → 系统和安全 → Windows Defender防火墙 → 高级设置 → 入站规则 → 新建规则开放5000端口

第二步:生产级部署(推荐方案)

建议使用Nginx反向代理 + Gunicorn部署方案:

1. 安装依赖
pip install gunicorn
sudo apt install nginx  # Linux
2. 通过Gunicorn启动应用
gunicorn -w 4 -b 0.0.0.0:8000 app:app
3. 配置Nginx反向代理

创建配置文件/etc/nginx/sites-available/flask_app

server {
    listen 80;
    server_name your_server_ip;  # 填写实际IP或域名

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
4. 启用配置
sudo ln -s /etc/nginx/sites-available/flask_app /etc/nginx/sites-enabled/
sudo nginx -t  # 测试配置
sudo systemctl restart nginx

第三步:安全加固

1. 配置HTTPS(强制推荐)

使用Let’s Encrypt免费证书:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_server_ip
2. 防火墙设置

仅开放必要端口:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw deny 5000/tcp  # 关闭原始端口

第四步:运行维护

1. 进程守护(示例用systemd)

创建服务文件/etc/systemd/system/flask_app.service

[Unit]
Description=Gunicorn instance for Flask App
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/usr/local/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app

[Install]
WantedBy=multi-user.target
2. 启动服务
sudo systemctl daemon-reload
sudo systemctl start flask_app
sudo systemctl enable flask_app

访问方式

  • 通过浏览器访问:
    http://your_server_ip       # HTTP
    https://your_server_ip      # HTTPS
    

注意事项

  1. 生产环境务必关闭debug=True
  2. 建议使用非root用户运行服务
  3. 定期更新服务器系统和Python依赖
  4. 监控服务器资源使用情况(可使用htop
  5. 重要数据建议配置自动备份

通过以上步骤,你的Flask应用即可安全地对外提供服务。如果需要更专业的部署方案(如Docker化、负载均衡),可进一步说明需求。

你可能感兴趣的:(python,html)