Django SyncDB and Perl Expect

I’m writing a database migration script in Perl to upgrade to a new database schema. This script often calls Django’s manage.py ‘syncdb’ function to rebuild from the new models. However, there’s one problem with this. Each time it runs, it asks the question:

You just installed Django’s auth system, which means you don’t have any superusers defined.
Would you like to create one now? (yes/no):

Well, I’m copying the data from the legacy database as soon as the new database is built, so no, I don’t want to create the new user. The problem though, is that this question comes up in the middle of the script, which can take up to an hour to run. This means I have to be attentive to the script. I can’t just start it and head to lunch. ‘Expect’ you say? Well, luckily There’s a Perl Module for that.

 Perl | 
 
 copy code |
?

01
02
use Expect;
03
use Term::ANSIColor;
04
# use Expect to automatically answer 'no' to the create superuser prompt
05
my $exp = Expect->spawn("../../syncdb.sh")
06
        or die ("Can't spawn ../../syncdb.sh");
07
 
08
# patidx = Pattern Index, the index of the last pattern matched, starting at 1
09
# so the 2nd pattern, which should be the last, leaves patidx at 2 if successful
10
my $patidx = $exp->expect(60,
11
        [qr'Would you like to create one now\? \(yes\/no\):',
12
                sub {$exp->send("no\n");exp_continue}],
13
        [qr'No fixtures found',
14
                sub {print color('Green'), "Finished syncdb.sh", color('Reset'), "\n";}],
15
        );
16
my $close_status =  $exp->soft_close();
17
if ($close_status != 0 and $patidx != 2) {
18
        print color('Red'), "Unknown error with syncdb.sh", color('Reset'), "\n";
19
        exit(1);
20
}
21

You may have to adjust the second matching pattern depending on your schema. This is the last line returned from the ‘manage.py syncdb’ script in my example.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *