Django文件在本地打开,但在服务器中失败

发布于 2025-01-21 11:45:25 字数 2558 浏览 2 评论 0原文

我想实现的是用户通过表单上传文件,以便说个人资料图片, 我的目的是获取该文件,通过IMGBB的API发送该文件,然后将图像URL存储在我的模板中。
我能够通过下面的代码(Windows)来实现这一目标,但是一旦我推向生产服务器(在这种情况下为Pythonanywhere),代码就会失败。

# CODE: 
def testingpage(request):
    image = ''
    url = ''

    if request.method == 'POST':
        pic = request.FILES['image']
        url = upload_to_bb(request, pic)
        if url is not None:
            from django.contrib import messages
            messages.info(request, 'Uploaded Successfully')

    return render(request, 'test.html', {'image': url})


def upload_to_bb(request, pic):
    import os
    from django.conf import settings
    from django.core.files.storage import FileSystemStorage
    import base64
    import requests

    base_url = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    fs = FileSystemStorage()
    filename = fs.save(pic.name, pic)
    file_path = f'{base_url}\media\{filename}'
    apikey = settings.IMGBB_API_KEY
    with open(file_path, "rb") as file:
        url = "https://api.imgbb.com/1/upload"
        payload = {
            "key": apikey,
            "image": base64.b64encode(file.read()),
        }
        r = requests.post(url, payload)
        js = r.json()
        if r.status_code == 200:
            data = js['data']
            file.close()
            os.remove(file_path)
            return data['image']['url']
        else:
            file.close()
            os.remove(file_path)
            from django.core.exceptions import ValidationError
            raise ValidationError("An error occurred processing the image")
    return None

罪魁祸首是

file_path = f'{base_url}\media\{filename}'

本地Windows Server上的这条代码线: 它返回

C:\Users\Sammy\PycharmProjects\kegites\media\WIN_20211209_15_41_37_Pro.jpg

在毕达尼亚(Pythonanywhere)上,我会遇到错误:

FileNotFoundError at /

[Errno 2] No such file or directory: '/home/kegitesclub/kegites\\media\\WIN_20211209_15_41_36_Pro_3afnrPi.jpg'

在Heroku上,我得到:

No such file or directory: '/app\\media\\WIN_20211209_15_41_37_Pro.jpg'

与Linux有关,这些服务器是其他问题,或者是其他东西,也许是Django限制?,或者您可以建议一种更好的方法来达到端结果?

任何帮助都将不胜感激的

是pythonanywhere:

”

映像链接: https://i.sstatic.net/quxpi.png

What I wanted to achieve was for a user to upload a file through a form, lets say profile picture,
My aim is to take that file, send it through imgbb's api and get the image url to store for use in my template later.
I was able to achieve this with the piece of code below, that works locally(Windows) but as soon as I push to my production server(pythonanywhere in this case), the code fails.

# CODE: 
def testingpage(request):
    image = ''
    url = ''

    if request.method == 'POST':
        pic = request.FILES['image']
        url = upload_to_bb(request, pic)
        if url is not None:
            from django.contrib import messages
            messages.info(request, 'Uploaded Successfully')

    return render(request, 'test.html', {'image': url})


def upload_to_bb(request, pic):
    import os
    from django.conf import settings
    from django.core.files.storage import FileSystemStorage
    import base64
    import requests

    base_url = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    fs = FileSystemStorage()
    filename = fs.save(pic.name, pic)
    file_path = f'{base_url}\media\{filename}'
    apikey = settings.IMGBB_API_KEY
    with open(file_path, "rb") as file:
        url = "https://api.imgbb.com/1/upload"
        payload = {
            "key": apikey,
            "image": base64.b64encode(file.read()),
        }
        r = requests.post(url, payload)
        js = r.json()
        if r.status_code == 200:
            data = js['data']
            file.close()
            os.remove(file_path)
            return data['image']['url']
        else:
            file.close()
            os.remove(file_path)
            from django.core.exceptions import ValidationError
            raise ValidationError("An error occurred processing the image")
    return None

the culprit is this line of code

file_path = f'{base_url}\media\{filename}'

On local windows server:
It returns

C:\Users\Sammy\PycharmProjects\kegites\media\WIN_20211209_15_41_37_Pro.jpg

on pythonanywhere, I get the error:

FileNotFoundError at /

[Errno 2] No such file or directory: '/home/kegitesclub/kegites\\media\\WIN_20211209_15_41_36_Pro_3afnrPi.jpg'

on heroku , I get:

No such file or directory: '/app\\media\\WIN_20211209_15_41_37_Pro.jpg'

Is it something to do with linux, that these servers are or is it something else, perhaps a Django limitation?, or can you suggest a better approach to reach end result?

Any help would be appreciated

StackTrace for pythonanywhere:

The stacktrace, it displays weirdly with copy/paste

Image link : https://i.sstatic.net/quXPI.png

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北方。的韩爷 2025-01-28 11:45:25

如果您需要具有系统不可知的路径(在Windows和Linux环境之间),请使用os.path.join,甚至更好的Pathlib来构建它们。

file_path = os.path.join(base_url, 'media', filename)

pathlib

base_url = pathlib.Path(__file__).resolve().parent.parent

,然后

file_path = base_url / 'media' / filename

If you need to have system agnostic paths (between Windows and Linux environments) use os.path.join or even better pathlib to build them.

file_path = os.path.join(base_url, 'media', filename)

or in case of pathlib

base_url = pathlib.Path(__file__).resolve().parent.parent

and then

file_path = base_url / 'media' / filename
檐上三寸雪 2025-01-28 11:45:25

continue

try changing this line from this

file_path = f'{base_url}\media\{filename}'

to this

file_path = f'{base_url}/media/{filename}'

and test it in the server

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文