从django下载sqlite文件

时间:2013-05-16 08:11:37

标签: python django

我有使用sqlite作为数据库的Django应用程序。 我不会查看能够下载该sqlite文件的视图。

这是我到目前为止所得到的:

def backup(request):
    """Return Sqlite3 db file, if Sqlite3 db is used."""
    import settings

    db_engine = settings.DATABASES['default']['ENGINE']
    #db_engine = 'JUST_FOR_TESTING'

    if db_engine == 'django.db.backends.sqlite3':
        db_path = settings.DATABASES['default']['NAME']

        response = HttpResponse(mimetype='application/x-sqlite3')
        response['Content-Disposition'] = 'attachment; filename=%s' % db_path
        response.write(db_path)

        return HttpResponse(response)
    else:
        return HttpResponse("settings.DATABASES['default']['ENGINE'] is %s,<br />\
                             only for 'django.db.backends.sqlite3' online backup is posible." % (db_engine))

我缺少的是如何将该文件添加为附件。

还有办法以某种方式只下载特定的表吗?

1 个答案:

答案 0 :(得分:5)

您只是尝试将文件路径作为附件发送。

相关代码是

    from django.core.files import File
    dbfile = File(open(db_path, "rb"))
    response = HttpResponse(dbfile, mimetype='application/x-sqlite3')
    response['Content-Disposition'] = 'attachment; filename=%s' % db_path
    response['Content-Length'] = dbfile.size

    return response