Maintain Constants.py through Data Migration

Sunday, March 14 2010 7:49 p.m.

This post will show you how to create a local_contants.py file using Django South. If you're not familiar with South, it's a data migration tool. Stated differently, it's a tool that helps keep your database changes current across different sandboxes and server environments.

The reason you may want to have constants is when you have a type model instance that you want to reference in your code for decision logic. For example, you might display things differently if your contact method type ID is 1 (email) vs 2 (phone). Typically, you keep these in constants.py file. Although sometimes you can put this data in a fixture, for various reasons sometimes fixtures is not the ideal solution.

The code below is designed to be run inside a migration to update your local_constants.py file with data that you just migrated. local_constants.py is a locally maintained file. This means, that like your local_settings.py, it should not be in the repo. For example:

set_constant('/home/projects/sample/local_constants.py', 'STAMP_MW_ID', 42
, 'Set from sample.0007_add_constants.py')


The constant searching could be improved, feel free to post enhancements!

def set_constant(file, constant, value, comment = ''):
    '''
    Search through file for the constant and either adds it to the end or 
    updates the existing value. Comment is optionally passed and is placed on
    the same line as the constant along with the modification date/time.
    Comment is only updated if the value is updated.
    
    It's recommended that the file for local_constants.py be different than the
    file checked into your repo as it's locally maintained.
    
    Example: set_constant('a.txt', 'TYPE', 1, 'This is optional')
    
    Author: Ed Menendez ([email protected])
    '''
    write_file = found_constant = False
    
    if comment:
        comment += ' '
    
    line_to_write = '%s = %s  # %sLast modified %s\n' % \
                    (constant, value.__repr__(), comment, datetime.datetime.now())
    
    # The file to be written is stored here.
    new_file = ''
    
    try:
        f = open(file, 'r+')
    except IOError:
        # Nothing to search through here. Move along.
        f = None
    else:
        # Loop through the file and look for the string
        for line in f.readlines():
            if line.find(constant) > -1:
                line_splits = line.split('=')
                
                if len(line_splits) == 2:
                    # Yes, it's an assignment line.
                    old_constant, old_value = line_splits
                    old_constant = old_constant.strip()
                
                    if old_constant == constant:
                        # We've found the contant!
                        found_constant = True
                        old_value_splits = old_value.split('#')
                        
                        if len(old_value_splits) == 2:
                            old_value, trash = old_value_splits
                        else:
                            old_value = old_value_splits[0]
                        
                        old_value = old_value.strip()
                    
                        if old_value != value.__repr__():
                            # It's changed!
                            write_file = True
                            line = line_to_write
            
            new_file += line

        f.close()

    # If nothing found, then add it to the end
    if not found_constant:
        write_file = True
        # New line needs to be added in case the file doesn't end with a new
        # line. Could be made smarter and check for the newline. This will make
        # for a prettier local_constants.py
        new_file += '\n' + line_to_write
    
    if write_file:
        # Write out the new file
        f = open(file, 'w+')
        f.write(new_file)
        f.close()

You can also find the code on DjangoSnippets.org

django, programming, python, south

Subscribe RSS Feed Bookmark and Share

More Blog Entries

Ed Menendez' Facebook profile