Flask应用
创建虚拟环境
$ python3 -m venv Flask_env
修改环境目录权限
$ sudo chown -R pi:pi Flask_env
激活虚拟环境
$ source Flask_env/bin/activate
安装Flask
$ pip install Flask
确认安装完成
$ pip list | grep Flask
Flask 3.0.3
创建一个file_operations.py程序
$ touch file_operations.py
写入如下内容
# 导入 Flask 和其他必要的模块
from flask import Flask, request, jsonify
import os
# 创建 Flask 应用实例
app = Flask(__name__)
# 定义创建文件的 API 路由
@app.route('/create_file', methods=['POST'])
def create_file():
# 获取请求中的 JSON 数据
data = request.json
# 从 JSON 数据中提取文件路径和内容
file_path = data.get('file_path')
content = data.get('content')
# 检查文件路径和内容是否为空
if not file_path or not content:
return jsonify({'error': 'file_path and content are required'}), 400
try:
# 打开文件并写入内容
with open(file_path, 'w') as file:
file.write(content)
# 返回成功消息
return jsonify({'message': f'File created at {file_path} with content: {content}'}), 200
except Exception as e:
# 捕获异常并返回错误消息
return jsonify({'error': str(e)}), 500
# 定义修改文件的 API 路由
@app.route('/modify_file', methods=['POST'])
def modify_file():
# 获取请求中的 JSON 数据
data = request.json
# 从 JSON 数据中提取文件路径和内容
file_path = data.get('file_path')
content = data.get('content')
# 检查文件路径和内容是否为空
if not file_path or not content:
return jsonify({'error': 'file_path and content are required'}), 400
# 检查文件是否存在
if not os.path.exists(file_path):
return jsonify({'error': f'File {file_path} does not exist'}), 404
try:
# 打开文件并写入新的内容
with open(file_path, 'w') as file:
file.write(content)
# 返回成功消息
return jsonify({'message': f'File modified at {file_path} with content: {content}'}), 200
except Exception as e:
# 捕获异常并返回错误消息
return jsonify({'error': str(e)}), 500
# 如果直接运行此文件,则启动 Flask 应用
if __name__ == '__main__':
# 启动 Flask 应用,监听所有网络接口的 5001 端口
app.run(host='0.0.0.0', port=5001)
运行该程序
$ python3 file_operations.py
* Serving Flask app 'file_operations'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5001
* Running on http://10.70.32.56:5001
Press CTRL+C to quit
通过本机或其他设备进行测试
创建文件
$ curl -X POST http://10.70.32.56:5001/create_file -H "Content-Type: application/json" -d '{"file_path":"/home/pi/new_file.txt", "content":"Hello, World!"}'
{"message":"File created at /home/pi/new_file.txt with content: Hello, World!"}
服务器控制台输出
10.70.32.107 - - [01/Nov/2024 08:35:56] "POST /create_file HTTP/1.1" 200 -
查看新文件
pi@raspberrypi:~ $ cat new_file.txt
Hello, World!
修改文件
$ curl -X POST http://10.70.32.56:5001/modify_file -H "Content-Type: application/json" -d '{"file_path":"/home/pi/new_file.txt", "content":"Hello, pi5!"}'
{"message":"File modified at /home/pi/new_file.txt with content: Hello, pi5!"}
服务器控制台输出
10.70.32.107 - - [01/Nov/2024 08:39:10] "POST /modify_file HTTP/1.1" 200 -
查看新文件
pi@raspberrypi:~ $ cat new_file.txt
Hello, pi5!