Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a management command in django views.py [duplicate]

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?

like image 617
Rafiul Sabbir Avatar asked Nov 04 '13 11:11

Rafiul Sabbir


2 Answers

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.

like image 117
Rohan Avatar answered Oct 24 '22 06:10

Rohan


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.

like image 29
shacker Avatar answered Oct 24 '22 06:10

shacker