7

I'm going to use django-dbbackup in my current application. My task is to take backup of my latest sqlite3 database with custom_name.db when 'Backup Database' button is pressed from the UI and to restore a backup from a list of existing backups when 'Restore this backup' is pressed.

In django-dbbackup there are two management commands, dbbackup and dbrestore which are used as

dbbackup [-s <servername>] [-d <database>] [--clean] [--compress] [--encrypt]

and

dbrestore [-d <database>] [-s <servername>] [-f <localfile>]

Now my question is, if I have the original db name original_db.db and I want to backup this db renaming as db_current_data_time.db, what should be the views.py methods?

Rafiul Sabbir
  • 626
  • 6
  • 21

2 Answers2

18

You can call commands run by manage.py using call_command

from django.core import management
management.call_command('your_command', your_options)

So in your respective views of backup and restore you can call your commands.

Rohan
  • 52,392
  • 12
  • 90
  • 87
  • Thanks for the answer. Can I just call the command using management.call_command() in views.py method? – Rafiul Sabbir Nov 05 '13 at 05:36
  • 1
    @iamrafiul, yes. But that will block the response to client. If you don't want that you can start new thread and run command in it. – Rohan Nov 05 '13 at 06:40
  • while executing it asking schema name in terminal (Enter DB Schema ('?' to list schemas): xxxx) where xxx name of the schema name???????????? so how to pass the schema name like interactive terminal so how to change user code according to my requirement – giveJob May 29 '18 at 09:25
7

While you can use call_command to call a management command, it is really not ideal. Management commands should be run interactively by a human from the shell, not called from a view.

If you want to offer both a management command and a web operation, move the guts of your management command into a separate function (I recommend myapp/operations/foo). Then refactor your management command to utilize this independent function. Once that's working, refactor your view to call the same operation (function), passing in the same arguments.

This will allow for optimal code sharing between the management command and the view, and will make writing tests for your core logic more sane.

shacker
  • 14,712
  • 8
  • 89
  • 89