2013-11-24 19 views
0

這真的讓我失望。我已經處理了好幾天了。在django中發送每個請求的郵件

當用戶從我的django網絡應用下載文件時,我想通過發送郵件通知上傳者他的文件已被下載。問題是,如果我應該下載一個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})),'[email protected]',[fileload.email,]) 
    return response 

download.txt

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

我怎麼能每次下載請求發送郵件?

+1

嘗試把sendmail的函數調用在一個單獨的功能,並從該視圖調用函數.. –

+0

我想這是因爲'範圍request'的。嘗試將狀態碼設置爲206(部分內容)。例如'response = HttpResponse(fileload.mov_file,content_type ='',status = 206)' – sha256

回答

1

我會建議不同的方法......

當有人下載​​文件,日誌中的事件表數據庫上。
編寫會話ID,文件名,用戶名。
請確保session_id + file_name + user_name是唯一密鑰
這樣,您可以獲得更多信息,以後可以爲您提供幫助。

稍後(作爲crontab批處理或保存監聽器)發送電子郵件。
你甚至可以發送每日/每週報告等等...

1

我想你會解決這個問題,只是這之後說:「不要用Django的文件服務解決方案」的最佳實踐。

取而代之,請在響應中使用X-Sendfile HTTP標頭,並配置您的網絡服務器來捕獲它並提供文件。如果您使用的是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