#!/usr/bin/env python2.4 # -*- encoding: iso-8859-1 -*- # vim: set et sw=4 sts=4 : # Módulos estándar import os import sys import locale import ConfigParser # Módulos externos import sqlobject # Módulos locales from sercom.dbo import * def ayuda(): return '''Uso: %s objeto comando [opciones]''' % sys.argv[0] def args2dict(l, conn): d = {'connection': conn} for arg in l: key, val = arg.split('=') if val == 'None': val = None d[key] = val return d if len(sys.argv) < 3: print >>sys.stderr, 'Faltan argumentos!' print >>sys.stderr, ayuda() sys.exit(1) # Seteo locale locale.setlocale(locale.LC_ALL, '') # Obtengo configuración conf = ConfigParser.SafeConfigParser() if not conf.read(('/etc/sercom/sercom.ini', os.path.expanduser('~/.sercom/sercom.ini'), 'sercom.ini')): sys.stderr.write('No se pudo obtener configuración!\n') sys.exit(1) # Conexión a la DB conn = sqlobject.connectionForURI(conf.get('dbo', 'database')) # Argumentos interesantes obj = sys.argv[1] try: pos = obj.index('.') attr = obj[pos+1:] obj = obj[:pos] except: attr = None cmd = sys.argv[2] oid = None args = sys.argv[3:] try: if sys.argv[3].isdigit(): oid = int(sys.argv[3]) args = sys.argv[4:] except: pass # Proceso comandos try: if cmd in ('list', 'ls'): if oid is not None: objs = [eval(obj).get(oid, connection=conn)] elif args: objs = eval(obj).selectBy(**args2dict(args, conn)) else: objs = eval(obj).select(connection=conn) for o in objs: if attr is None: print o else: print o print attr + ':' import pprint attr = eval('o.' + attr) pprint.pprint(attr) elif cmd in ('rm', 'remove', 'delete', 'del'): if oid is not None: objs = [eval(obj).get(oid, connection=conn)] else: objs = eval(obj).selectBy(args2dict(args, conn)) for o in objs: print 'Borrando:', o o.destroySelf() elif cmd in ('set', 'update'): if oid is not None: objs = [eval(obj).get(oid, connection=conn)] else: where = args[:args.index('--')] args = args[args.index('--')+1:] objs = eval(obj).selectBy(**args2dict(where, conn)) for o in objs: print 'Modificando:', o, o.set(**args2dict(args, conn)) print '->', o elif cmd in ('add', 'new', 'insert'): o = eval(obj)(**args2dict(args, conn)) print 'Agregado:', o else: print >>sys.stderr, 'Comando incorrecto (%s)!' % cmd print >>sys.stderr, ayuda() sys.exit(2) except ValueError: print >>sys.stderr, 'Argumento inválido!' print >>sys.stderr, ayuda() sys.exit(3) except Exception, msg: print >>sys.stderr, 'ERROR:', msg sys.exit(100)