gpt4 book ai didi

python - 在 Django 中测试 ajax 文件上传时出现奇怪的错误

转载 作者:行者123 更新时间:2023-11-28 20:24:36 26 4
gpt4 key购买 nike

我正在尝试 在 django 中上传 ajax 文件。我编写了 javascript,django view 如下。文件上传成功。然后我写了一个测试方法 View 。执行测试时,文件成功上传到目标文件夹。但是,我收到一些奇怪的错误。

在应用程序中执行ajax上传时不会出现此特定错误。它仅在执行测试时出现。

$(document).ready(function(){
$(document).on('change', '#fileselect', function(e){
e.preventDefault();
uploadFile(e);
});

function uploadFile(e){
var form = $('#fileform').get(0);
var formData = new FormData(form);
var file = $('#fileselect').get(0).files[0];
var xhr = new XMLHttpRequest();
formData.append('file', file);
xhr.open('POST', 'upload/', true);
xhr.send(formData);

xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
var data = $.parseJSON(xhr.responseText);
var uploadResult = data['message']

if (uploadResult=='failure'){
displayErrorMessage('failed to upload');
}else if (uploadResult=='success'){
}
}
}
}
...

django View

def ajax_upload(request):
retvals = {}
message="failure"
if (request.method == 'POST'):
if request.FILES.has_key('file'):
file = request.FILES['file']
print 'file=',file
with open(settings.uploadfolder+'/'+fname, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
message="success"
retvals['message']= message
serialized = json.dumps(retvals)
print 'serialized=',serialized
if message == "success":
print 'success'
return HttpResponse(serialized, mimetype="application/json")
else:
return HttpResponseServerError(serialized, mimetype="application/json")

urls.py 文件的片段

网址.py

...
url(r'^upload/$', 'myapp.views.ajax_upload',name='ajax_upload'),
...

最后是测试方法

class UploadTest(TestCase):
def setUp(self):
super(UploadTest,self).setUp()
self.client.login(username='me',password='mypass')

def test_upload(self):
fname = os.path.join(settings.testfolder,'mydoc.doc')
with open(fname) as fp:
resp = self.client.post(self.client.post(reverse('ajax_upload'),{'file':fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))

如您所见,我在 View 代码中放置了一些打印语句,它们显示 request.FILES['file'] 具有正确的值(即 mydoc. doc) 并且上传成功(我可以看到文件已复制到dest文件夹)。

现在这是显示错误消息的控制台输出

file= mydoc.doc
serialized= {"message": "success"}
success
E
======================================================================
ERROR: test_upload (myapp.tests.UploadTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/me/dev/python/django/myapp/tests.py", line 143, in test_upload_file
resp = self.client.post(self.client.post(reverse('ajax_upload'),{'file':fp}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
File "/home/me/Django-1.4/django/test/client.py", line 449, in post
response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
File "/home/me/Django-1.4/django/test/client.py", line 252, in post
parsed = urlparse(path)
File "/usr/lib/python2.6/urlparse.py", line 108, in urlparse
tuple = urlsplit(url, scheme, allow_fragments)
File "/usr/lib/python2.6/urlparse.py", line 147, in urlsplit
i = url.find(':')
AttributeError: 'HttpResponse' object has no attribute 'find'

----------------------------------------------------------------------
Ran 1 test in 0.200s

FAILED (errors=1)

我无法弄清楚为什么会发生这种情况..有人可以帮我解决这个问题吗?

最佳答案

resp = self.client.post(self.client.post(...))

别担心,每个人都会遇到 :)

关于python - 在 Django 中测试 ajax 文件上传时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com