开发者

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.DATA开发者_如何学运维BASE_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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜