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!