Присоединенный путь SuspiciousFileOperation, расположенный вне компонента базового пути - PullRequest
0 голосов
/ 17 июня 2019

При выполнении следующего теста я получаю SuspiciousFileOperation

from django.conf import settings
from django.contrib.auth import get_user_model
import pytest

User = get_user_model()
settings.CONNECT_HOT_FOLDER = f"{settings.ROOT_DIR}\\media\\hot_folder\\"
settings.MEDIA_ROOT = f"{settings.ROOT_DIR}\\media\\"  # <-- this was the issue!!


def image_for_test():
    employee = Employee.objects.create(core_id='1000', connect_id=1, connect_username='HOPCOBROKER.Test',)
    user = User.objects.create(username="hopcobroker\\test", employee=employee,)
    receipt = Receipt.objects.create(receipt_date=now(), description="test", amount=100.0, employee=user)
    image = ReceiptImage.objects.create(image=r'test_files\breaking_image.jpg', receipt=receipt,)
    return employee, user, receipt, image


@pytest.mark.django_db(transaction=True)
def test_convert_creates_csv_and_pdf_file(clean_up_test_files_in_hot_folder, settings):
    employee, user, receipt, image = image_for_test()
    pdf_file = f'{settings.CONNECT_HOT_FOLDER}\\{receipt.id}.pdf'
    csv_file = f'{settings.CONNECT_HOT_FOLDER}\\{receipt.id}.csv'

    convert(receipt)

    assert os.path.isfile(pdf_file)
    assert os.path.isfile(csv_file)
class ReceiptImage(models.Model):
    image = models.ImageField(upload_to='images/%Y/%m/')
    receipt = models.ForeignKey(
        Receipt,
        on_delete=models.CASCADE,
        related_name='images',
    )
    active = models.BooleanField(default=True)
    meta_data = fields.JSONField(blank=True, null=True)

При открытии и изображении с библиотекой PIL, как показано ниже

from PIL import Image
from .models import ReceiptImage
image = ReceiptImage.objects.filter(receipt=receipt)

img = Image.open(image.image)

Я получаю следующую ошибку ...

Сообщение об ошибке:

base = 'C:\\code\\receipts\\media\\'
paths = ('test_files\\no_meta_data_picture.png',)
final_path = 'C:\\code\\receipts\\media\\test_files\\no_meta_data_picture.png'
base_path = 'C:\\code\\receipts\\media\\'

    def safe_join(base, *paths):
        """
        Join one or more path components to the base path component intelligently.
        Return a normalized, absolute version of the final path.

        Raise ValueError if the final path isn't located inside of the base path
        component.
        """
        final_path = abspath(join(base, *paths))
        base_path = abspath(base)
        # Ensure final_path starts with base_path (using normcase to ensure we
        # don't false-negative on case insensitive operating systems like Windows),
        # further, one of the following conditions must be true:
        #  a) The next character is the path separator (to prevent conditions like
        #     safe_join("/dir", "/../d"))
        #  b) The final path must be the same as the base path.
        #  c) The base path must be the most root path (meaning either "/" or "C:\\")
        if (not normcase(final_path).startswith(normcase(base_path + sep)) and
                normcase(final_path) != normcase(base_path) and
                dirname(normcase(base_path)) != normcase(base_path)):
            raise SuspiciousFileOperation(
                'The joined path ({}) is located outside of the base path '
>               'component ({})'.format(final_path, base_path))
E           django.core.exceptions.SuspiciousFileOperation: The joined path (C:\code\receipts\media\test_files\no_meta_data_picture.png) is located outside of the base path component (C:\code\receipts\media\)

Сообщение об ошибке сверху

django.core.exceptions.SuspiciousFileOperation: Объединенный путь (C: \ code \ recets \ media \ test_files \ no_meta_data_picture.png) расположен вне компонента базового пути (C: \ code \ receivets \ media)

... что не имеет большого смысла для меня. В сообщении об ошибке он говорит мне, каковы основные и конечные пути. Последний путь находится в базовом пути.

Ниже приведена соответствующая часть файла настроек. Глядя на другие решения, я пытался добавить или удалить трейлинг \ или / безрезультатно. Я на Windows 10.

settings.py

ROOT_DIR = (
    environ.Path(__file__) - 3  # (C:\code\receipts\config(3)\settings(2)\base.py(1) )
)
MEDIA_ROOT = os.path.join(ROOT_DIR, "media")

Любая помощь приветствуется, спасибо!

...