在djang按请求发送邮件

2024-09-24 22:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这真是让我难受。我已经处理这件事好几天了。你知道吗

当用户从我的django web应用下载文件时,我想通过发送邮件通知上传者他的文件已经下载。问题是,如果我下载一个low file size (489kb),它会发送一个mail once to the uploader。但是如果我要下载一个file size of 3mb or above,它会发送more than one mail to the uploader。你知道吗

我只想它发送一个邮件通知到上传每次下载。你知道吗

视图:

@login_required
def document_view(request,emov_id):
    fileload = Emov.objects.get(id=emov_id)
    filename = fileload.mov_file.name.split('/')[-1]
    filesize=fileload.mov_file.size
    response = HttpResponse(fileload.mov_file, content_type='') 
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    response['Content-Length'] = filesize    
    send_mail('Your file has just been downloaded',loader.get_template('download.txt').render(Context({'fileload':fileload})),'test@example.com',[fileload.email,])
    return response

你知道吗下载.txt你知道吗

'Your file {{ fileload.name}} have been downloaded!'

如何为每个下载请求发送邮件?你知道吗


Tags: 文件thetoidsizegetresponse邮件
2条回答

我认为您可以通过以下最佳实践来解决这个问题,即“不要向Django提供文件”。你知道吗

相反,在您的响应中使用X-sendfilehttp头,并配置您的web服务器来捕获它并提供文件。如果您使用的是Apache,请参阅this。你知道吗

然后,创建如下响应:

response = HttpResponse()
response['X-Sendfile'] = unicode(filename).encode('utf-8')
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment; filename="%s"' % filename
response['Content-length'] = filesize  # Optional
return response

我建议另一种方法。。。你知道吗

当有人下载文件时,将事件记录到数据库的表中
写下会话ID、文件名和用户名。
确保session\u id+file\u name+user\u name是唯一键 这样,你可以得到更多的信息,可以帮助你以后。你知道吗

稍后(作为crontab批处理或保存侦听器)发送电子邮件。
你甚至可以发送每日/每周报告等等。。。你知道吗

相关问题 更多 >