【发布时间】:2019-03-14 07:16:06
【问题描述】:
我的网站上有一个页面,用户可以在其中使用 ajax 上传 xlsx 文件,在后端我读取文件,进行一些处理并开始将其行一一插入到我的数据库中。如果用户上传的文件非常大,在数据库中输入新值可能需要一段时间。因此,我想在他们的屏幕上为用户提供实时进度更新,例如。 -
Found 100 rows of data
Interesting 1/100.
Interesting 2/100.
...
Interesting 100/100.
Done.
我的观点:
import pandas as pd
def myView(self, request):
"""Handle POST requests, save all data provided in excel file."""
excel_file = request.FILES.get('excel_one')
excel_df = pd.read_excel(excel_file)
data_format = ['Option_1', 'Option_2', 'Option_3', 'Option_4',]
try:
formatted_df = excel_df[data_format]
except KeyError as error:
return JsonResponse({'success': False, 'message': str(error), })
# forloop to create model objects
for i, v in formatted_df.iterrows():
# do a lot of data validating and stuff first
MyModels.objects.create(arguments)
print(f'Created object {i+1}/{len(formatted_df)}!' # Want to to be sent to html page in real time
return JsonResponse({'success': True, })
我正在发出这样的 ajax 请求:
$.ajax({ // variables url, data, etc. contain the expected stuff
async: false,
url: url,
method: "POST",
data: data,
success: function(d){
if(data.success){
console.log(d);
}
else{
$('.log').append('<p><b>Error:</b> '+ d.message +'</p>')
}
},
cache: false,
contentType: false,
processData: false
});
在数据库中保存数据和其他一切都按预期工作,但我只是不知道如何将实时更新发送到 ajax。我能想到的一种可能的解决方案是实现 Web 套接字而不是普通的 http 请求,但我有点着急,所以有什么方法可以用简单的 js 和 django 来实现。
【问题讨论】:
标签: python ajax django python-3.x django-views