Changeset 12624 for trunk


Ignore:
Timestamp:
03/28/11 16:48:56 (13 years ago)
Author:
sil
Message:
  • refactored some code
  • removed CMTTemplate-specific code
  • removed obsolete code
  • output of templates is generated more efficiently
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/sara_cmt/cmt.py

    r12458 r12624  
    8989
    9090# Setup the logger for logging
    91 loglevel_str = config_parser.get('defaults', 'LOGLEVEL')
    92 logger.setLevel(config_parser.getint('loglevels', loglevel_str))
     91loglevel = config_parser.get('defaults', 'LOGLEVEL')
     92if loglevel == 'NOTSET' and settings.DEBUG == True:
     93    logger.setLevel(config_parser.getint('loglevels', 'DEBUG'))
     94else:
     95    logger.setLevel(config_parser.getint('loglevels', loglevel))
    9396
    9497
     
    248251
    249252def generate(option, opt_str, value, parser, *args, **kwargs):
    250     from sara_cmt.template import CMTTemplate
    251253    from django.template import Context
    252254
    253255    # Save full path of templatefile to generate
    254     filename = value
     256    template_filename = value
    255257
    256258    # Make a dict with filenames of the available templates
     
    264266        i+=1
    265267
    266     if filename[-4:] != '.cmt':
    267         filename += '.cmt'
     268    if template_filename[-4:] != '.cmt':
     269        template_filename += '.cmt'
    268270
    269271    # Loop until a valid template has been chosen by the user
    270     while filename not in fdict.values():
    271         logger.warning("File '%s' not known"%filename)
     272    while template_filename not in fdict.values():
     273        logger.warning("File '%s' not known"%template_filename)
    272274
    273275        # Give a numbered overview of the available templates
     
    275277            print '%s : %s'%(str(key).rjust(2),val)
    276278        logger.debug('fdict: %s'%fdict.values())
    277         filename = raw_input('\nChoose: ')
     279        template_filename = raw_input('\nChoose: ')
    278280
    279281        # If number given, lookup the filename in the dictionary
    280         if filename.isdigit():
    281             num = int(filename)
     282        if template_filename.isdigit():
     283            num = int(template_filename)
    282284            if num <= len(fdict):
    283                 filename = fdict[num]
    284                 logger.debug('filename: %s'%filename)
     285                template_filename = fdict[num]
     286                logger.debug('filename: %s'%template_filename)
    285287            else:
    286288                continue
    287289        # Else check for the extension
    288         elif filename[-4:]!='.cmt':
    289             filename+='.cmt'
    290 
    291         logger.debug('%s (%s)'%(filename,type(filename)))
    292 
    293     fullpath = os.path.join(settings.CMT_TEMPLATES_DIR, filename)
    294 
    295     # Load the contents of the templatefile as a CMTTemplate
     290        elif template_filename[-4:] != '.cmt':
     291            template_filename += '.cmt'
     292
     293        logger.debug('%s (%s)'%(template_filename,type(template_filename)))
     294
     295    template_fullpath = os.path.join(settings.CMT_TEMPLATES_DIR, template_filename)
     296
    296297    try:
    297         f = open(fullpath, 'r')
    298         templatestr = f.read()
    299         f.close()
    300 
    301         template = CMTTemplate(templatestr)
    302 
    303         # Render the CMTTemplate with a Context
     298        # Initialize a Context to render the template with
    304299        template_data = {}
    305300        template_data['version'] = CMTSARA_VERSION
    306301        template_data['svn_id'] = '$Id:$'
    307302        template_data['svn_url'] = '$URL:$'
    308         template_data['input'] = fullpath
    309         template_data['stores'] = { }
    310 
    311         c = Context(template_data)
    312         res = template.render(c)
    313 
    314         # While rendering the CMTTemplate there are variables added to the
    315         # context, so these can be used for post-processing.
    316 
    317         ### <DEBUG>
    318         logger.debug('<RESULT>\n%s'%res)
    319         logger.debug('</RESULT>')
    320         ### </DEBUG>
     303        template_data['input'] = template_fullpath
     304        template_data['__template_outputfiles__'] = {} # reserved for data to write to files
     305        context = Context(template_data)
     306
     307        template_data['stores'] = template_data['__template_outputfiles__'] # to stay bw compatible with ramon's code (temporary)
     308       
     309        rendered_string = render_to_string(template_filename, context_instance=context)
     310        # While rendering the template there are variables added to the
     311        # Context, so these can be used for post-processing.
     312        logger.debug('<RESULT>\n%s\n</RESULT>'%rendered_string)
     313
    321314    except IOError, e:
    322315        logger.error('Template does not exist: %s' % e)
    323316
    324     if not parser.values.DRYRUN: # Write output file(s)
    325317       
    326         c['stores'] = c['stores'] or {c['output']:res}
    327 
    328         for store_file, store_output in c['stores'].items():
    329 
    330             write_msg = 'Writing outputfile: %s' %store_file
    331             created_msg = 'Outputfile(s) created: %s' %store_file
    332 
     318    for outputfile, content in context['__template_outputfiles__'].items():
     319        write_msg = 'Writing outputfile: %s' % outputfile
     320        created_msg = 'Outputfile(s) created: %s' % outputfile
     321
     322        if not parser.values.DRYRUN: # Write output file(s)
    333323            try:
    334324                logger.info(write_msg)
    335                 f = open(store_file, 'w')
    336                 f.writelines(store_output)
     325                f = open(outputfile, 'w')
     326                f.writelines(content)
    337327                f.close()
    338328                logger.info(created_msg)
     
    340330                logger.error('Failed creating outputfile: %s' % e)
    341331            except KeyError, e:
    342                 logger.error('No output/stores defined in template')
    343 
    344     else:
    345         logger.info('[DRYRUN] Not writing files' )
    346         logger.info('[DRYRUN] Nothing created' )
     332                logger.error('No outputfiles defined in template')
     333        else:
     334            write_msg = '[DRYRUN] %s' % write_msg
     335            created_msg = '[DRYRUN] %s' % created_msg
     336            logger.info(write_msg)
     337            logger.info(created_msg)
    347338
    348339    if not parser.values.DRYRUN:
    349340        try:
    350             for script in c['epilogue']:
    351                 ### <DEBUG>
    352                 logger.info('Now executing epilogue script')
    353                 #logger.debug('<EPILOGUE>')
     341            for script in context['epilogue']:
     342                logger.info('Executing epilogue script')
    354343                os.system(script)
    355                 #logger.debug('</EPILOGUE>')
    356344                logger.info('Finished epilogue script')
    357                 ### </DEBUG>
    358345        except KeyError, e:
    359             logger.info('Did not find an epilogue script')
     346            logger.debug('No epilogue script found')
    360347    return
    361348
    362349
    363 #def mac(option, opt_str, value, parser, *args, **kwargs):
    364 #    """
    365 #        Change the MAC-address of an existing interface.
    366 #    """
    367 #    old_mac, new_mac = value
    368 #
    369 #    query = {'ent': search_model('interface'),
    370 #        'get': {'hwaddress': [old_mac]}, 'set': {'hwaddress': [new_mac]}}
    371 #
    372 #    _object = object_mgr.get_object(query)
    373 #
    374 #    if _object:
    375 #        logger.debug('Found a unique object matching query: %s' % _object)
    376 #        confirmed = not parser.values.INTERACTIVE or \
    377 #            raw_input('Are you sure? [Yn] ')
    378 #        if confirmed in ['', 'y', 'Y', True]:
    379 #            attr_set_msg = 'Attributes has been set: %s' % _object
    380 #            if not parser.values.DRYRUN:
    381 #                _object.setattrs_from_dict(query['set'])
    382 #                logger.debug(attr_set_msg)
    383 #            else:
    384 #                logger.debug('[DRYRUN] %s' % attr_set_msg)
    385 #        else:
    386 #            logger.info('Change of MAC-address has been cancelled')
    387 #    else:
    388 #        logger.error('Unable to execute this request')
    389 
    390 #
    391 # </Database related methods>
    392 #
    393 #####
    394 
    395 
    396350#####
    397351#
    398352# <Methods for processing of arguments>
    399353#
    400 #def collect_args(option):
    401354
    402355
     
    495448                        The query, which consists out of one or more terms, is
    496449                        used to make a selection of objects to list.""")
    497 #    parser.add_option('-m', '--mac',
    498 #                    action='callback',
    499 #                    callback=mac,
    500 #                    type='string',
    501 #                    metavar='<old MAC> <new MAC>',
    502 #                    nargs=2,
    503 #                    help='Change the MAC-address of an interface')
    504450    parser.add_option('-r', '--remove',
    505451                    action='callback',
Note: See TracChangeset for help on using the changeset viewer.