picomon
picomon

Reputation: 1519

Send mail per request in django

This is really killing me. I've been dealing with this for days.

When a user download a file from my django web app, I want to notify the uploader that his file has been downloaded by sending a mail. The problem is, If I should download a low file size (489kb), it will send a mail once to the uploader. But if I should download a file size of 3mb or above it will send more than one mail to the uploader.

I just want it to send one mail notification to the uploader per download.

views:

@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!'

How can I send mail per download request?

Upvotes: 0

Views: 172

Answers (2)

knaperek
knaperek

Reputation: 2233

I think you would solve this problem just with following best practises which say "Do not serve files with Django".

Instead, use X-Sendfile HTTP header in your response and configure your webserver to catch it and serve the file. See this if you're using Apache.

Then, create the response as follows:

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

Upvotes: 1

Izack
Izack

Reputation: 843

I would suggest a different approach...

When someone download the file, log the event to a table on your database.
Write the Session ID, the file name, the user name.
Make sure that session_id+file_name+user_name are unique key
This way, you can get much more information that can help you later.

Later on (as a crontab batch, or save listener) send the emails.
You can even send a daily/weekly report and so on...

Upvotes: 1

Related Questions