简体   繁体   中英

Want to create a view which can dump mysql database as a sql file

I seem to be having a problem. I want to write some code that can dump a mysql database, when an administrator user clicks on a button. I have tried writing some code in my views.py below.

Views.py

    @login_required
    def dbbackup(request):
        if not (request.user.is_authenticated() and request.user.is_staff):
            raise http.Http404
        os.chdir('/usr/local/src/djcode/c2duo_mms')  # This is important as apache by default goes to the user's home directory.
        os.popen3("mysqldump --add-drop-table -u " + settings.DATABASE_USER + " -p" + settings.DATABASE_PASSWORD + " " + settings.DATABASE_NAME + " >  backup.sql")
        os.popen3("gzip -c backup.sql > backup.gz")

Now is giving me an error The view c2duo_mms.mmc.views.dbbackup didn't return an HttpResponse object. If I add return HttpResponse at the end. it will say unbound method has_header() must be called with HttpResponse instance as first argument (got str instance instead) .

I'm not very sure what the problem is. but I cannot work out the solution. I sort of stuck now.

You need to return a valid HttpResponse object from the end of your method. For example, if you wanted to return the gzip file:

@login_required
def dbbackup(request):
    if not (request.user.is_authenticated() and request.user.is_staff):
        raise http.Http404
    os.chdir('/usr/local/src/djcode/c2duo_mms')  # This is important as apache by default goes to the user's home directory.
    os.popen3("mysqldump --add-drop-table -u " + settings.DATABASE_USER + " -p" + settings.DATABASE_PASSWORD + " " + settings.DATABASE_NAME + " >  backup.sql")
    os.popen3("gzip -c backup.sql > backup.gz")
    dataf = open('/usr/local/src/djcode/c2duo_mms/backup.gz', 'r')
    return HttpResponse(dataf.read(), mimetype='application/x-gzip')

This should initiate a download of the gzip file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM