Wednesday, August 24, 2016

Adding a container class for auth credentials.

First we are going add a container class for the service credentials we need to pass around.  I would also suppose that if we were going to encrypt these values, that having this container class be the place where the data is encrypted/decrypted makes sense (but we're not doing that right now).



So we start out simply enough.  I put the file in the "Helpers" directory.  As mentioned before, I didn't put it in DataObjects, because I only want tests and associated files to access the regular data objects.


 class CredsContainer:  
   
   consumer_key = None  
   consumer_secret = None  
   access_token = None,  
   access_token_secret = None  
   
   def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):  
     self.consumer_key = consumer_key  
     self.consumer_secret = consumer_secret  
     self.access_token = access_token  
     self.access_token_secret = access_token_secret  
   

You can see this is pretty easy here.  It's just a place to store our auth creds.  I modified Config to store auth creds in this class, and the service classes to accept the class as parameters


   # Warning! The code to set up logging requires this config class. Do not do any logging in read_config  
   def read_config(self):  
     config = configparser.ConfigParser()  
     config.read(self.config_file_name)  
     self.twitter_auth_creds = CredsContainer(config[self.COMMON_CONFIG_SECTION]['consumer_key'],  
                          config[self.COMMON_CONFIG_SECTION]['consumer_secret'],  
                          config[self.COMMON_CONFIG_SECTION]['access_token'],  
                          config[self.COMMON_CONFIG_SECTION]['access_token_secret'])  
     self.logging_level = config[self.COMMON_CONFIG_SECTION]['logging_level']  
     self.logging_path = config[self.COMMON_CONFIG_SECTION]['logging_path']  
   

I'm not sure posting WebServiceBase, and TwitterStatusesService again with the changes are worth it.  They simply use the creds from the container class, instead of having each parameter in the constructor.  I will, however show how much less messy it is to instantiate a new twitter service class:

   def setup_class(self):  
     self.config = conftest.get_config(pytest.config)  
     self.logger = logging.getLogger(Config.LOGGER_ID)  
     self.twitter_service = TwitterStatusesService(self.config.twitter_api_base_url,  
                            self.config.twitter_auth_creds,  
                            Config.LOGGER_ID)  
   

No comments:

Post a Comment