Changeset 76 for trunk/dbpickle/dbpickle.py
- Timestamp:
- 02/27/07 10:24:21 (3 years ago)
- Files:
-
- 1 modified
-
trunk/dbpickle/dbpickle.py (modified) (8 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/dbpickle/dbpickle.py
r75 r76 31 31 primary key. ManyToMany and OneToOne relations are not supported. 32 32 33 You can also use you own plugin for pre-processing objects before 34 saving them into the database. This is useful e.g. when a model has 35 changed and you're importing objects from an old version of the 36 database. The plugin should be a Python program with a 37 `pre_save_hook(obj)` function which returns True if it modified the 38 object, otherwise False. 39 40 41 Usage example 42 ============= 43 33 44 Let's suppose your project is using PostgreSQL and the database has 34 45 been populated using the app. … … 56 67 import logging 57 68 from django.db import models 69 from imp import load_source 58 70 59 71 def dump(filepath): … … 72 84 73 85 @transaction.commit_on_success 74 def load(filepath ):86 def load(filepath, pluginpath=None): 75 87 """ 76 88 Unpickle Django objects from the given file and save them into the 77 89 database. 78 90 """ 91 92 if pluginpath: 93 plugin = load_source('plugin', pluginpath) 94 else: 95 plugin = None 96 97 pre_save_hook = getattr(plugin, 'pre_save_hook', lambda obj: False) 79 98 80 99 # unpickle objects from file … … 90 109 while data: 91 110 key, obj = data.popitem() 92 load_recursive(data, obj )111 load_recursive(data, obj, pre_save_hook) 93 112 94 113 95 def load_recursive(data, obj ):114 def load_recursive(data, obj, pre_save_hook): 96 115 """ 97 116 Save the given object into the database. If the object has … … 109 128 related_model, 110 129 related_pk_val)) 111 load_recursive(data, related_obj )130 load_recursive(data, related_obj, pre_save_hook) 112 131 except KeyError: 113 132 logging.debug('probably loaded already: ' … … 116 135 logging.info('loading %s' % obj) 117 136 try: 137 pre_save_hook(obj) 118 138 obj.save() 119 139 except Exception, e: … … 127 147 p.add_option('-l', '--load', action='store_const', const='load', dest='action', help='Load all Django objects from a file') 128 148 p.add_option('-f', '--file', default='djangodb.pickle', help='Specify file path [djangodb.pickle]') 149 p.add_option('-p', '--plugin', help='Use .py plugin for preprocessing objects to load') 129 150 p.add_option('-v', '--verbose' , action='store_true', help='Show verbose output for debugging') 130 151 (opts, args) = p.parse_args() … … 134 155 dump(opts.file) 135 156 elif opts.action == 'load': 136 load(opts.file )157 load(opts.file, opts.plugin) 137 158 else: 138 159 print 'Please specify --dump or --load'
