如何在django中将文件流式传输到客户端 [英] how to stream file to client in django
问题描述
我想知道如何使用 django 将数据流式传输到客户端.
I want to know how can I stream data to client using django.
目标
用户提交一个表单,表单数据被传递给一个返回一个字符串的网络服务.字符串被压缩 (tar.gz
) 并且 tarball 被发送回用户.
The user submits a form, the form data is passed to a web service which returns a string. The string is tarballed (tar.gz
) and the tarball is sent back to the user.
我不知道是怎么回事.我搜索并找到了 this,但我只有一个字符串,我不知道是不是我想要的东西,我不知道用什么来代替 filename = __file__
,因为我没有文件 - 只是一个字符串.如果我为每个用户创建一个新文件,这将不是一个好方法.所以请帮助我.(抱歉,我是网络编程新手).
I don't know what's the way. I searched and I found this, but I just have a string and I don't know if it is the thing I want, I don't know what to use in place of filename = __file__
, because I don't have file - just a string. If I create a new file for each user, this won't be a good way. so please help me. (sorry I'm new in web programming).
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#mainForm").serialize();
$.ajax({
type: "POST",
data: temp,
url: 'main/',
success: function(data) {
$("#mainDiv").html(data.form);
????
}
});
});
我想使用ajax,那么我该怎么做才能成功使用ajac函数并返回视图.真的谢谢.
I want to use ajax, so what should i do in success of ajac function and in return of view. really thanks.
我的view.py:
def idsBackup(request):
if request.is_ajax():
if request.method == 'POST':
result = ""
form = mainForm(request.POST)
if form.is_valid():
form = mainForm(request.POST)
//do form processing and call web service
string_to_return = webserviceString._result
???
to_json = {}
to_json['form'] = render_to_string('main.html', {'form': form}, context_instance=RequestContext(request))
to_json['result'] = result
???return HttpResponse(json.dumps(to_json), mimetype='application/json')
else:
form = mainForm()
return render_to_response('main.html', RequestContext(request, {'form':form}))
else:
return render_to_response("ajax.html", {}, context_instance=RequestContext(request))
推荐答案
您可以创建 ContentFile 使用字符串内容而不是实际文件,然后将其作为响应发送.
You can create a django file instance of ContentFile using a string content instead of actual file and then send it as a response.
示例代码:
from django.core.files.base import ContentFile
def your_view(request):
#your view code
string_to_return = get_the_string() # get the string you want to return.
file_to_send = ContentFile(string_to_return)
response = HttpResponse(file_to_send,'application/x-gzip')
response['Content-Length'] = file_to_send.size
response['Content-Disposition'] = 'attachment; filename="somefile.tar.gz"'
return response
这篇关于如何在django中将文件流式传输到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!