<commit_before>#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4

import time, datetime, os
import threading
import traceback

import component
import log

class Router (component.Receiver):
    incoming_phases = ('parse', 'handle', 'cleanup')
    outgoing_phases = ('outgoing',)

    def __init__(self):
        component.Receiver.__init__(self)
        self.backends = []
        self.apps = []
        self.running = False
        self.logger = None

    def log(self, level, msg, *args):
        self.logger.write(self, level, msg, *args)

    def set_logger(self, level, file):
        self.logger = log.Logger(level, file)

    def build_component (self, class_template, conf):
        """Imports and instantiates an module, given a dict with 
           the config key/value pairs to pass along."""
        # break the class name off the end of the module template
        # i.e. "apps.%s.app.App" -> ("apps.%s.app", "App")
        module_template, class_name = class_template.rsplit(".",1)
       
        # make a copy of the conf dict so we can delete from it
        conf = conf.copy()

        # resolve the component name into a real class
        module_name = module_template % (conf.pop("type"))
        module = __import__(module_name, {}, {}, [''])
        component_class = getattr(module, class_name)
        
        # create the component with an instance of this router
        # and keep hold of it here, so we can communicate both ways
        title = conf.pop("title")
        component = component_class(title, self)
        try:
            component.configure(**conf)
        except TypeError, e:
            # "__init__() got an unexpected keyword argument '...'"
            if "unexpected keyword" in e.message:
                missing_keyword = e.message.split("'")[1]
                raise Exception("Component '%s' does not support a '%s' option."
                        % (title, missing_keyword))
            else:
                raise
        return component

    def add_backend (self, conf):
        try:
            backend = self.build_component("rapidsms.backends.%s.Backend", conf)
            self.info("Added backend: %r" % conf)
            self.backends.append(backend)
            
        except:
            self.log_last_exception("Failed to add backend: %r" % conf)
            

    def add_app (self, conf):
        try:
            app = self.build_component("apps.%s.app.App", conf)
            self.info("Added app: %r" % conf)<commit_msg>adding a name property to the PersistantBackend. adding a method to the router to get a backend by name<commit_after>#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4

import time, datetime, os
import threading
import traceback

import component
import log

class Router (component.Receiver):
    incoming_phases = ('parse', 'handle', 'cleanup')
    outgoing_phases = ('outgoing',)

    def __init__(self):
        component.Receiver.__init__(self)
        self.backends = []
        self.apps = []
        self.running = False
        self.logger = None

    def log(self, level, msg, *args):
        self.logger.write(self, level, msg, *args)

    def set_logger(self, level, file):
        self.logger = log.Logger(level, file)

    def build_component (self, class_template, conf):
        """Imports and instantiates an module, given a dict with 
           the config key/value pairs to pass along."""
        # break the class name off the end of the module template
        # i.e. "apps.%s.app.App" -> ("apps.%s.app", "App")
        module_template, class_name = class_template.rsplit(".",1)
       
        # make a copy of the conf dict so we can delete from it
        conf = conf.copy()

        # resolve the component name into a real class
        module_name = module_template % (conf.pop("type"))
        module = __import__(module_name, {}, {}, [''])
        component_class = getattr(module, class_name)
        
        # create the component with an instance of this router
        # and keep hold of it here, so we can communicate both ways
        title = conf.pop("title")
        component = component_class(title, self)
        try:
            component.configure(**conf)
        except TypeError, e:
            # "__init__() got an unexpected keyword argument '...'"
            if "unexpected keyword" in e.message:
                missing_keyword = e.message.split("'")[1]
                raise Exception("Component '%s' does not support a '%s' option."
                        % (title, missing_keyword))
            else:
                raise
        return component

    def add_backend (self, conf):
        try:
            backend = self.build_component("rapidsms.backends.%s.Backend", conf)
            self.info("Added backend: %r" % conf)
            self.backends.append(backend)
            
        except:
            self.log_last_exception("Failed to add backend: %r" % conf)
            

    def get_backend (self, name):
        '''gets a backend by name, if it exists'''
        for backend in self.backends:
            if backend.name == name:
                return backend
        return None

    def add_app (self, conf):
        try:
            app = self.build_component("apps.%s.app.App", conf)
            self.info("Added app: %r" % conf)
{'fraction_non_alphanumeric': 0.10935143288084465, 'fraction_numerical': 0.001885369532428356, 'mean_word_length': 2.0932944606413995, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3790396', 'n_tokens_mistral': 1485, 'n_tokens_neox': 1452, 'n_words': 470}