Django文件在本地打开,但在服务器中失败
我想实现的是用户通过表单上传文件,以便说个人资料图片, 我的目的是获取该文件,通过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:
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:
Image link : https://i.sstatic.net/quXPI.png
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要具有系统不可知的路径(在Windows和Linux环境之间),请使用
os.path.join
,甚至更好的Pathlib
来构建它们。或
pathlib
,然后
If you need to have system agnostic paths (between Windows and Linux environments) use
os.path.join
or even betterpathlib
to build them.or in case of
pathlib
and then
continue
try changing this line from this
to this
and test it in the server