Django文件上传处理程序错误 [英] Django File Upload Handler Errors

查看:142
本文介绍了Django文件上传处理程序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我希望在收到指定的扩展程序后立即停止任何不结束的文件上传。为此,我定义一个自定义的上传处理程序,并写入new_file,看起来像这样:

  def new_file(self,field_name, file_name,content_type,content_length,charset = None):
basename,extension = os.path.splitext(file_name)
如果扩展名为.txt:
raise StopUpload(True)#错误:只有.txt文件被接受

这样可以停止上传,但它也会清除请求。文件。现在,当我的视图收到请求时,它无法告诉上传处理程序是否导致文件丢失,我无法向用户显示有用的消息。



有没有办法将上传处理程序中的邮件传播到相应的视图,以便我可以向用户显示错误?我试过使用请求对象,但它是不可变的。

解决方案

我找到了一个为什么我不能t

$ b

看来Django会使用懒惰评估来请求.FILES到
确定上传时间处理程序被调用。因此,上传
处理程序仅在您尝试访问
request.FILES时才被引用。另外,我使用
(在我的情况下是WSGIRequest)的请求对象已经使GET和POST不可变字典
,所以我们不能通过那里传递信息。然而,META仍然是
可用于添加信息。



我的组合解决方案在
处理视图中有request.FILES行上传,这迫使上传处理程序开始。当new_files中的
错误被捕获时,我将self.request.META ['error']设置为
的错误消息,并提高StopUpload,这将推送回
视图而无需文件。最后,我在
视图中检查request.META ['error'],并在出现问题时显示该消息。



希望这有帮助!


In Django, I want to stop any file uploads that don't end in my designated extension as soon as they're received. To do this, I define a custom Upload Handler and write new_file to look something like this:

def new_file(self, field_name, file_name, content_type, content_length, charset=None):
    basename, extension = os.path.splitext(file_name)
    if extension != ".txt":
        raise StopUpload(True) # Error: Only .txt files are accepted

This works fine for stopping the upload but it also clears request.FILES. Now, when my view receives the request, it has no way to telling whether the upload handler caused the file to be missing and I can't display a useful message to the user.

Is there any way to propagate messages from the Upload Handler to the corresponding view, such that I can display the error to the user? I've tried using the request object, but it is immutable.

解决方案

I've found a reason for why I couldn't get it working and a solution as well.

It would appear that Django uses lazy evaluation for request.FILES to determine when the upload handler is called. Therefore, the upload handler is only evoked when and if you attempt to access request.FILES. Additionally, the request object I am using (WSGIRequest in my case) has made GET and POST immutable dictionaries, so we can't pass information through there. However, META is still available to add information to.

My combined solution has the line "request.FILES" in the view that handles uploads, which forces the upload handler to begin. When the error is captured in new_files, I set self.request.META['error'] to the error message and raise StopUpload, which pushes us back into the view without a file. Finally, I check for request.META['error'] in the view and display that message when there is a problem.

I hope this helps!

这篇关于Django文件上传处理程序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆