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
Python函数调用示例以下是实现该功能的完整步骤和代码示例:
使用Python Flask框架搭建后端,HTML+JavaScript作为前端,实现前后端交互。
pip install flask
your_project/
├── app.py # 后端代码
├── templates/
│ └── index.html # 前端页面
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)
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>
python app.py
http://localhost:5000
cac_sum()
函数cac_sum()
函数内容这个方案实现了基本的网页调用Python函数功能,可以根据实际需求进一步扩展功能。
要实现通过公网IP让所有人访问你的Flask网页应用,需要以下步骤:
在启动应用时添加host=0.0.0.0
参数:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=False) # 关闭调试模式
sudo ufw allow 5000/tcp
sudo ufw reload
建议使用Nginx反向代理 + Gunicorn部署方案:
pip install gunicorn
sudo apt install nginx # Linux
gunicorn -w 4 -b 0.0.0.0:8000 app:app
创建配置文件/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;
}
}
sudo ln -s /etc/nginx/sites-available/flask_app /etc/nginx/sites-enabled/
sudo nginx -t # 测试配置
sudo systemctl restart nginx
使用Let’s Encrypt免费证书:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_server_ip
仅开放必要端口:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw deny 5000/tcp # 关闭原始端口
创建服务文件/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
sudo systemctl daemon-reload
sudo systemctl start flask_app
sudo systemctl enable flask_app
http://your_server_ip # HTTP
https://your_server_ip # HTTPS
debug=True
htop
)通过以上步骤,你的Flask应用即可安全地对外提供服务。如果需要更专业的部署方案(如Docker化、负载均衡),可进一步说明需求。