This is the view-code to export a database-dump (hardcoded for mysql) or a media_root dump via the admin interface.
just add 2 urls patterns to call the views and a small template with a simple form to send a http-post to the views.
Note: The downloads are sort of streaming. I have successfully exportet a 2GB media_root as tar-ball without major increase of ram-usage of the django-process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import os
from datetime import date
from django.conf import settings
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
def export_database(request):
if not request.method == 'POST':
return render_to_response('admin/export.html', {'what': 'Database',})
else:
#output backup
cmd = settings.MYSQLDUMP_BIN+' --opt --compact --skip-add-locks -u %s -p%s %s | bzip2 -c' % (settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DATABASE_NAME)
stdin, stdout = os.popen2(cmd)
stdin.close()
response = HttpResponse(stdout, mimetype="application/octet-stream")
response['Content-Disposition'] = 'attachment; filename=%s' % date.today().__str__()+'_db.sql.bz2'
return response
@staff_member_required
def export_media(request):
if not request.method == 'POST':
return render_to_response('admin/export.html', {'what': 'Media Root',})
else:
#output media
stdin, stdout = os.popen2('tar -cf - %s' % settings.MEDIA_ROOT)
stdin.close()
#print "created process, closed stdin"
response = HttpResponse(stdout, mimetype="application/octet-stream")
response['Content-Disposition'] = 'attachment; filename=%s' % date.today().__str__()+'_media.tar'
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Don't forget to set
MYSQLDUMP_BIN
in your settings file to the path of yourmysqldump
binary before using this, e.g."/usr/bin/mysqldump"
.#
I am having a few problems with this.
One initial small thing - you may need to include -h and then your database hostname if your database isn't localhost from Django.
I've got the following:
Anyway - that didn't quite get me working - Basically it doesn't like streaming from stdout. I add to add the line: stdout = stdout.readlines()
and remove the pipe to bzip to get any output. This is on the dev server and on Django over FCGI
#
Quick update - the above problems with streaming might be middleware related.
#
Please login first before commenting.