# 导入 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!"}