我有一个令人困惑的“FileNotFoundError: [Errno 2] No such file or directory:”

时间:2021-03-26 13:08:17

标签: python flask

我遇到了一个非常令人困惑的 FileNotFoundError。 这是确切的错误:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\opt\\flogger\\static\\images\\uploads\\ad142cb9-1d55-4cce-9bbc-a984344f65bb.png'

这是关于错误的附加信息:

File "C:\Users\Kyrios\opt\flogger\blog\views.py", line 40, in post

 [Open an interactive python shell in this frame] Image.open(f).save(file_path)

File "C:\Users\Kyrios\opt\flogger\venv\Lib\site-packages\pil\Image.py", line 2161, in save

 [Open an interactive python shell in this frame] fp = builtins.open(filename, "w+b")

这是代码:

image_id = None

        if form.image.data:
            f = form.image.data
            image_id = str(uuid.uuid4())
            file_name = image_id + '.png'
            file_path = os.path.join(
                BLOG_POST_IMAGES_PATH, file_name
            )
            Image.open(f).save(file_path)

            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 600, 'lg')
            _image_resize(BLOG_POST_IMAGES_PATH, image_id, 300, 'sm')

_image_resize 函数:

def _image_resize(original_file_path, image_id, image_base, extension):
    file_path = os.path.join(
        original_file_path, image_id + '.png'
    )
    image = Image.open(file_path)
    wpercent = (image_base / float(image.size[0]))
    hsize = int((float(image.size[1]) * float(wpercent)))
    image = image.resize((image_base, hsize), Image.ANTIALIAS)
    modified_file_path = os.path.join(
        original_file_path, image_id + '.' + extension + '.png'
    )
    image.save(modified_file_path)
    return

这是文件路径

BLOG_POST_IMAGES_PATH='C:\opt\flogger\static\images\uploads'

该目录存在,但它一直说它不存在,这令人困惑。这是 uuid 模块的问题还是其他问题?进口是:

from flask import Blueprint, session, render_template, redirect, url_for, flash, request
from slugify import slugify
import uuid
import os
from pil import Image
from settings import BLOG_POST_IMAGES_PATH

settings.py:

import os

SECRET_KEY=os.environ['SECRET_KEY']
DB_USERNAME=os.environ['DB_USERNAME']
DB_PASSWORD=os.environ['DB_PASSWORD']
DB_HOST=os.environ['DB_HOST']
DATABASE_NAME=os.environ['DATABASE_NAME']
DB_URI = f"mysql+pymysql://{DB_USERNAME}:{DB_PASSWORD}@{DB_HOST}:3306/{DATABASE_NAME}"
SQLALCHEMY_DATABASE_URI = DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = True
MYSQL_ROOT_PASSWORD = os.environ['MYSQL_ROOT_PASSWORD']
BLOG_NAME = os.environ['BLOG_NAME']
BLOG_POST_IMAGES_PATH = os.environ['BLOG_POST_IMAGES_PATH']

ps。哦,pil 是小写字母是因为 PIL 不起作用它不断收到 nomodule 错误,我在我的站点包中找到的文件是小写字母

1 个答案:

答案 0 :(得分:0)

是的,答案只是用实际的完整路径替换“C:\opt\flogger\static\images\uploads”。用户 Wander Nauta 感谢您的洞察力