Ubuntu服务器Flask应用报FileNotFoundError,Windows运行正常
Flask应用Ubuntu服务器报错FileNotFoundError:找不到./images路径(本地正常)
问题描述
在DigitalOcean Ubuntu Droplet上部署Flask应用时返回内部服务器错误,错误提示找不到路径./images/ISIC_0029612.jpg.jpg,但当前代码中无任何涉及该路径的读写逻辑。本地Windows 11环境运行正常,已尝试重启/重载uwsgi、nginx服务,问题未解决。
错误堆栈信息
File "/var/www/html/cancel-the-cancer/venv/lib/python3.10/site-packages/flask/views.py", line 107, in view return current_app.ensure_sync(self.dispatch_request)(**kwargs) File "/var/www/html/cancel-the-cancer/venv/lib/python3.10/site-packages/flask_restful/__init__.py", line 582, in dispatch_request resp = meth(*args, **kwargs) File "/var/www/html/cancel-the-cancer/Resources/predict.py", line 10, in post img = img.resize((256, 256)) File "/var/www/html/cancel-the-cancer/venv/lib/python3.10/site-packages/werkzeug/datastructures.py", line 3002, in save dst = open(dst, "wb") FileNotFoundError: [Errno 2] No such file or directory: './images/ISIC_0029612.jpg.jpg'
相关代码
predict.py
import numpy as np from flask_restful import Resource, request import tensorflow as tf from PIL import Image class Predict(Resource): def post(self): file = request.files['image'] img = Image.open(file.stream) img = img.resize((256, 256)) img = np.array(img) img = img / 255.0 img = np.expand_dims(img, axis=0) loaded_model = tf.keras.models.load_model('../model/vgg19_92%_93%') prediction = loaded_model.predict(img)[0][0] return {"result": float(prediction)}
app.py
import flask_restful from flask_cors import CORS from flask_cors import CORS from flask import Flask from flask_restful import Api from Resources.predict import Predict app = Flask(__name__) app.secret_key = 'zwolnienizteorii44893' api = Api(app) cors = CORS(app) api.add_resource(Predict, '/predict') if __name__ == '__main__': app.run(port=5000, debug=True)
解决方案
1. 创建缺失的images目录并设置权限
虽然代码中未显式使用该目录,但依赖库可能隐式需要它,执行以下命令:
sudo mkdir /var/www/html/cancel-the-cancer/images sudo chown www-data:www-data /var/www/html/cancel-the-cancer/images sudo chmod 755 /var/www/html/cancel-the-cancer/images
2. 统一PIL/Pillow版本(本地与服务器一致)
不同操作系统下的版本差异可能导致对象行为异常:
- 本地Windows执行
pip show pillow获取版本号 - 服务器执行以下命令安装对应版本:
/var/www/html/cancel-the-cancer/venv/bin/pip install pillow==<本地版本号>
3. 修改代码确保Image对象完全加载到内存
避免流对象隐式触发磁盘操作,修改predict.py中图片处理部分:
file = request.files['image'] # 转换为RGB格式并确保加载到内存 img = Image.open(file.stream).convert('RGB') img = img.resize((256, 256))
4. 检查uwsgi工作目录配置
确保uwsgi配置文件(如uwsgi.ini)中的chdir参数指向应用根目录:
chdir = /var/www/html/cancel-the-cancer
修改后重启uwsgi:
sudo systemctl restart uwsgi
内容的提问来源于stack exchange,提问作者Wiktor Fajkowski
相关产品推荐
相关产品推荐

