def call(): log_instance = Logger.get_instance( level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") user = UserSignature(email="*****@*****.**") token = OAuthToken(client_id="clientId", client_secret="clientSecret", token="REFRESH/ GRANT Token", token_type=TokenType.REFRESH / TokenType.GRANT) environment = USDataCenter.PRODUCTION() store = FileStore( file_path='/Users/username/Documents/python_sdk_tokens.txt') resource_path = '/Users/user_name/Documents/python-app' sdk_config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) Initializer.initialize(user, environment, token, store, sdk_config, resource_path, log_instance) module_1 = "Leads" module_2 = "Contacts" response_1 = RecordOperations().get_records(module_1) response_2 = RecordOperations().get_records(module_2)
def file_exists_flow(module_api_name, record_field_details_path, last_modified_time): with Utility.lock: record_field_details_json = Initializer.get_json(record_field_details_path) initializer = Initializer.get_initializer() if initializer.sdk_config.get_auto_refresh_fields() and not Utility.new_file and not Utility.get_modified_modules and (Constants.FIELDS_LAST_MODIFIED_TIME not in record_field_details_json or Utility.force_refresh or (time.time() * 1000 - record_field_details_json[Constants.FIELDS_LAST_MODIFIED_TIME]) > 3600000): Utility.get_modified_modules = True last_modified_time = record_field_details_json[Constants.FIELDS_LAST_MODIFIED_TIME] if not Utility.force_refresh and Constants.FIELDS_LAST_MODIFIED_TIME in record_field_details_json else None Utility.modify_fields(record_field_details_path, last_modified_time) Utility.get_modified_modules = False elif not Initializer.get_initializer().sdk_config.get_auto_refresh_fields() and Utility.force_refresh and not Utility.get_modified_modules: Utility.get_modified_modules = True Utility.modify_fields(record_field_details_path, last_modified_time) Utility.get_modified_modules = False record_field_details_json = Initializer.get_json(record_field_details_path) if module_api_name is None or (module_api_name.lower() in record_field_details_json and record_field_details_json[module_api_name.lower()] is not None): return else: Utility.fill_data_type() record_field_details_json[module_api_name.lower()] = {} Utility.write_to_file(file_path=record_field_details_path, file_contents=record_field_details_json) field_details = Utility.get_fields_details(module_api_name) record_field_details_json = Initializer.get_json(record_field_details_path) record_field_details_json[module_api_name.lower()] = field_details Utility.write_to_file(file_path=record_field_details_path, file_contents=record_field_details_json)
def set_api_url(self, connector): try: from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer except Exception: from ..initializer import Initializer api_path = '' if Constants.HTTP in self.__api_path: if Constants.CONTENT_API_URL in self.__api_path: api_path = Initializer.get_initializer( ).environment.file_upload_url try: url_parse = urllib3.util.parse_url(self.__api_path) path = url_parse.path except Exception as ex: raise SDKException(code=Constants.INVALID_URL_ERROR, cause=ex) api_path = api_path + path else: if str(self.__api_path)[:1].__eq__('/'): self.__api_path = self.__api_path[1:] api_path = api_path + self.__api_path else: api_path = Initializer.get_initializer().environment.url api_path = api_path + self.__api_path connector.url = api_path
def call(): log_instance = Logger.get_instance(level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") user1 = UserSignature("*****@*****.**") token1 = OAuthToken(client_id="clientId1", client_secret="clientSecret1", token="REFRESH/ GRANT Token", token_type=TokenType.REFRESH / TokenType.GRANT, redirect_url="redirectURL") environment = USDataCenter.PRODUCTION() store = DBStore() resource_path = '/Users/user_name/Documents/python-app' user1_module_api_name = 'Leads' user2_module_api_name = 'Contacts' user2 = UserSignature("*****@*****.**") token2 = OAuthToken(client_id="clientId2", client_secret="clientSecret2", redirect_url="redirectURL", token="REFRESH/ GRANT Token", token_type=TokenType.REFRESH / TokenType.GRANT) sdk_config_1 = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) sdk_config_2 = SDKConfig(auto_refresh_fields=False, pick_list_validation=False) Initializer.initialize(user1, environment, token1, store, sdk_config_1, resource_path, log_instance) single_thread = SingleThread(environment, token1, user1, user1_module_api_name, sdk_config_1) single_thread.run() single_thread = SingleThread(environment, token2, user2, user2_module_api_name, sdk_config_2) single_thread.run()
def call(): log_instance = Logger.get_instance(Logger.Levels.INFO, "/Users/Documents/multi_thread_logs.txt") user = UserSignature("*****@*****.**") token = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", refresh_token="refresh token") environment = USDataCenter.PRODUCTION() store = DBStore() resource_path = '/Users/Documents' sdk_config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) Initializer.initialize(user, environment, token, store, sdk_config, resource_path, log_instance) module_1 = "Leads" module_2 = "Contacts" response_1 = RecordOperations().get_records(module_1) response_2 = RecordOperations().get_records(module_2)
def call(): log_instance = Logger.get_instance(Logger.Levels.INFO, "/Users/Documents/multi_thread_logs.txt") user = UserSignature("*****@*****.**") token = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", refresh_token="refresh token") environment = USDataCenter.PRODUCTION() store = DBStore() resource_path = '/Users/Documents' sdk_config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) Initializer.initialize(user, environment, token, store, sdk_config, resource_path, log_instance) t1 = MultiThread('Leads') t2 = MultiThread('Deals') t1.start() t2.start() t1.join() t2.join()
def get_module_names(): module_data = {} resources_path = os.path.join(Initializer.get_initializer().resource_path, Constants.FIELD_DETAILS_DIRECTORY) if not os.path.exists(resources_path): os.makedirs(resources_path) record_field_details_path = Utility.get_file_name() is_null = False if os.path.exists(record_field_details_path): json = Initializer.get_json(record_field_details_path) if Constants.SDK_MODULE_METADATA not in json: is_null = True elif json[Constants.SDK_MODULE_METADATA] is None or len(json[Constants.SDK_MODULE_METADATA])==0: is_null = True if not os.path.exists(record_field_details_path) or is_null: module_data = Utility.get_modules(None) Utility.write_module_meta_data(record_field_details_path, module_data) return module_data record_field_details_json = Initializer.get_json(record_field_details_path) module_data = record_field_details_json[Constants.SDK_MODULE_METADATA] return module_data
def call(): log_instance = Logger.get_instance( level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") user = UserSignature("*****@*****.**") token = OAuthToken(client_id="clientId", client_secret="clientSecret", token="REFRESH/ GRANT Token", token_type=TokenType.REFRESH / TokenType.GRANT) environment = USDataCenter.PRODUCTION() store = DBStore() resource_path = '/Users/user_name/Documents/python-app' sdk_config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) Initializer.initialize(user, environment, token, store, sdk_config, resource_path, log_instance) t1 = MultiThread('Leads') t2 = MultiThread('Deals') t1.start() t2.start() t1.join() t2.join()
def initialize_sdk(): # Create an instance of Logger Class that takes two parameters # 1 -> Level of the log messages to be logged. Can be configured by typing Levels "." and choose any level from the list displayed. # 2 -> Absolute file path, where messages need to be logged. logger_instace = Logger.get_instance( level=Logger.Levels.INFO, file_path="/Users/user_name/Documents/python_sdk_log.log") # Create an UserSignature instance that takes user Email as parameter user = UserSignature(email="*****@*****.**") """ Create a Token instance that takes the following parameters 1 -> OAuth client id. 2 -> OAuth client secret. 3 -> OAuth redirect URL. 4 -> REFRESH/GRANT token. 5 -> token type. """ token = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", token="REFRESH/ GRANT Token", token_type=TokenType.REFRESH / TokenType.GRANT) # Configure the environment # which is of the pattern Domain.Environment # Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter # Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() environment = USDataCenter.PRODUCTION() # Create an instance of TokenStore """ Create an instance of TokenStore 1 -> Absolute file path of the file to persist tokens """ store = FileStore( file_path='/Users/username/Documents/python_sdk_tokens.txt') """ Create an instance of SDKConfig """ config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) """ The path containing the absolute directory path (in the key resource_path) to store user-specific files containing information about fields in modules. """ resource_path = '/Users/user_name/Documents/python-app' """ Call the static initialize method of Initializer class that takes the following arguments 1 -> UserSignature instance 2 -> Environment instance 3 -> Token instance 4 -> TokenStore instance 5 -> SDKConfig instance 6 -> resource_path 7 -> Logger instance """ Initializer.initialize(user, environment, token, store, config, resource_path, logger_instace)
def run(self): try: Initializer.switch_user(self.user, self.environment, self.token, self.sdk_config, self.proxy) print('Getting records for User: '******'Status Code: ' + str(response.get_status_code())) if response.get_status_code() in [204, 304]: print('No Content' if response.get_status_code() == 204 else 'Not Modified') return # Get object from response response_object = response.get_object() if response_object is not None: # Check if expected ResponseWrapper instance is received. if isinstance(response_object, ResponseWrapper): # Get the list of obtained Record instances record_list = response_object.get_data() for record in record_list: for key, value in record.get_key_values().items(): print(key + " : " + str(value)) # Check if the request returned an exception elif isinstance(response_object, APIException): # Get the Status print("Status: " + response_object.get_status().get_value()) # Get the Code print("Code: " + response_object.get_code().get_value()) print("Details") # Get the details dict details = response_object.get_details() for key, value in details.items(): print(key + ' : ' + str(value)) # Get the Message print("Message: " + response_object.get_message().get_value()) except Exception as e: print(e)
def generate_id(self): id = "" email = str(Initializer.get_initializer().user.get_email()) environment = str(Initializer.get_initializer().environment.name) id += Constants.PYTHON + email[0:email.find(Constants.AT )] + Constants.UNDERSCORE id += environment + Constants.UNDERSCORE + self.__refresh_token[ len(self.__refresh_token) - 4:] self.__id = id return self.__id
def get_related_lists(related_module_name, module_api_name, common_api_handler): with Utility.lock: try: is_new_data = False key = (module_api_name + Constants.UNDERSCORE + Constants.RELATED_LISTS).lower() resources_path = os.path.join( Initializer.get_initializer().resource_path, Constants.FIELD_DETAILS_DIRECTORY) if not os.path.exists(resources_path): os.makedirs(resources_path) record_field_details_path = Utility.get_file_name() if not os.path.exists(record_field_details_path) or ( os.path.exists(record_field_details_path) and key not in Initializer.get_json(record_field_details_path) ): is_new_data = True related_list_values = Utility.get_related_list_details( module_api_name) record_field_details_json = Initializer.get_json( record_field_details_path) if os.path.exists( record_field_details_path) else {} record_field_details_json[key] = related_list_values Utility.write_to_file( file_path=record_field_details_path, file_contents=record_field_details_json) record_field_details_json = Initializer.get_json( record_field_details_path) module_related_list = record_field_details_json[key] if not Utility.check_related_list_exists( related_module_name, module_related_list, common_api_handler) and not is_new_data: del record_field_details_json[key] Utility.write_to_file( file_path=record_field_details_path, file_contents=record_field_details_json) Utility.get_related_lists(related_module_name, module_api_name, common_api_handler) except SDKException as e: Utility.logger.error(Constants.EXCEPTION + e.__str__()) raise e except Exception as e: sdk_exception = SDKException(cause=e) Utility.logger.error(Constants.EXCEPTION + sdk_exception.__str__()) raise sdk_exception
def run(self): try: Initializer.switch_user(self.user, self.environment, self.token, self.sdk_config) print('Getting records for User: ' + Initializer.get_initializer().user.email) response = RecordOperations().get_records(self.module_api_name) print(response) except Exception as e: print(e)
def call(): log_instance = Logger.get_instance(Logger.Levels.INFO, "/Users/Documents/logs.txt") user1 = UserSignature("*****@*****.**") token1 = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", refresh_token="refresh token") environment = USDataCenter.PRODUCTION() sdk_config_1 = SDKConfig(auto_refresh_fields=False, pick_list_validation=True) # store = DBStore(password='******') store = FileStore("/Users/Documents/token.txt") resource_path = '/Users/Documents/' auto_refresh_fields = True user1_module_api_name = 'Leads' user2_module_api_name = 'Contacts' user2 = UserSignature("*****@*****.**") token2 = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", refresh_token="refresh token") proxy_user2 = RequestProxy('host', 8080) sdk_config_2 = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) Initializer.initialize(user1, environment, token1, store, sdk_config_1, resource_path, log_instance) t1 = MultiThread(environment, token1, user1, user1_module_api_name, sdk_config_1) t2 = MultiThread(environment, token2, user2, user2_module_api_name, sdk_config_2, proxy_user2) t1.start() t2.start() t1.join() t2.join()
def authenticate(self, url_connection): with OAuthToken.lock: initializer = Initializer.get_initializer() store = initializer.store user = initializer.user if self.__access_token is None: if self.__id is not None: oauth_token = initializer.store.get_token_by_id( self.__id, self) else: oauth_token = initializer.store.get_token(user, self) else: oauth_token = self if oauth_token is None: token = self.generate_access_token( user, store).get_access_token() if ( self.__refresh_token is None ) else self.refresh_access_token(user, store).get_access_token() elif oauth_token.get_expires_in() is not None and int( oauth_token.get_expires_in()) - int( time.time() * 1000) < 5000: OAuthToken.logger.info(Constants.REFRESH_TOKEN_MESSAGE) token = oauth_token.refresh_access_token( user, store).get_access_token() else: token = oauth_token.get_access_token() url_connection.add_header(Constants.AUTHORIZATION, Constants.OAUTH_HEADER_PREFIX + token)
def generate_access_token(self, user, store): try: url = Initializer.get_initializer().environment.accounts_url body = { Constants.GRANT_TYPE: Constants.GRANT_TYPE_AUTH_CODE, Constants.CLIENT_ID: self.client_id, Constants.CLIENT_SECRET: self.client_secret, Constants.REDIRECT_URL: self.redirect_url, Constants.CODE: self.grant_token } response = requests.post(url, data=body, params=None, headers=None, allow_redirects=True).json() store.save_token(user, self.parse_response(response=response)) except SDKException as ex: raise ex except Exception as ex: raise SDKException(code=Constants.SAVE_TOKEN_ERROR, cause=ex) return self
def refresh_access_token(self, user, store): try: url = Initializer.get_initializer().environment.accounts_url body = { Constants.REFRESH_TOKEN: self.__refresh_token, Constants.CLIENT_ID: self.__client_id, Constants.CLIENT_SECRET: self.__client_secret, Constants.GRANT_TYPE: Constants.REFRESH_TOKEN } response = requests.post(url, data=body, params=None, headers=None, allow_redirects=False).json() self.parse_response(response) if self.__id is None: self.generate_id() store.save_token(user, self) except SDKException as ex: raise ex except Exception as ex: raise SDKException(code=Constants.SAVE_TOKEN_ERROR, cause=ex) return self
def __delete_fields(module): """ The method to delete fields of the given module from the current user's fields JSON file. Parameters: module(str): A string representing the module. Raises: SDKException """ try: record_field_details_path = os.path.join( ModuleFieldsHandler.__get_directory(), Converter.get_encoded_file_name()) if os.path.exists(record_field_details_path): record_field_details_json = Initializer.get_json( record_field_details_path) Utility.delete_fields(record_field_details_json, module) with open(record_field_details_path, mode="w") as file: json.dump(record_field_details_json, file) file.flush() file.close() except Exception as e: sdk_exception = SDKException(cause=e) raise sdk_exception
def __get_module_detail_from_user_spec_json(self, module): try: import os from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer except Exception: import os from ..initializer import Initializer record_field_details_path = os.path.join( Initializer.get_initializer().resource_path, Constants.FIELD_DETAILS_DIRECTORY, Converter.get_encoded_file_name()) record_field_details = Initializer.get_json(record_field_details_path) module_detail = Utility.get_json_object(record_field_details, module) return module_detail
def call(): log_instance = Logger.get_instance(Logger.Levels.INFO, "/Users/Documents/logs_3.8.txt") user1 = UserSignature("*****@*****.**") token1 = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", refresh_token="refresh token") environment = USDataCenter.PRODUCTION() store = DBStore() resource_path = '/Users/Documents' auto_refresh_fields = True user1_module_api_name = 'Leads' user2_module_api_name = 'Contacts' user2 = UserSignature("*****@*****.**") token2 = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", refresh_token="refresh token") sdk_config_1 = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) sdk_config_2 = SDKConfig(auto_refresh_fields=False, pick_list_validation=False) Initializer.initialize(user1, environment, token1, store, sdk_config_1, resource_path, log_instance) single_thread = SingleThread(environment, token1, user1, user1_module_api_name, sdk_config_1) single_thread.run() single_thread = SingleThread(environment, token2, user2, user2_module_api_name, sdk_config_2) single_thread.run()
def get_encoded_file_name(cls): """ The method to get the module field JSON details file name. :return: A str representing the module field JSON details file name. """ try: from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer except Exception: from ..initializer import Initializer file_name = Initializer.get_initializer().user.email file_name = file_name.split( "@", 1)[0] + Initializer.get_initializer().environment.url input_bytes = file_name.encode("UTF-8") encoded_string = base64.b64encode(input_bytes) encoded_string = str(encoded_string.decode("UTF-8")) return encoded_string + '.json'
def __get_directory(): """ The method to obtain resources directory path. Returns: str: A String representing the directory's absolute path. """ return os.path.join(Initializer.get_initializer().resource_path, Constants.FIELD_DETAILS_DIRECTORY)
def verify_module_api_name(module_api_name): if module_api_name is not None and module_api_name.lower() in Constants.DEFAULT_MODULE_NAME_VS_API_NAME and Constants.DEFAULT_MODULE_NAME_VS_API_NAME.get(module_api_name.lower()) is not None: return Constants.DEFAULT_MODULE_NAME_VS_API_NAME.get(module_api_name.lower()) record_field_details_path = Utility.get_file_name() if os.path.exists(record_field_details_path): fields_json = Initializer.get_json(record_field_details_path) if Constants.SDK_MODULE_METADATA in fields_json and module_api_name.lower() in fields_json[Constants.SDK_MODULE_METADATA]: return fields_json[Constants.SDK_MODULE_METADATA][module_api_name.lower()][Constants.API_NAME] return module_api_name
def modify_fields(record_field_details_path, modified_time): modified_modules = Utility.get_modules(modified_time) record_field_details_json = Initializer.get_json(record_field_details_path) record_field_details_json[Constants.FIELDS_LAST_MODIFIED_TIME] = time.time() * 1000 Utility.write_to_file(file_path=record_field_details_path, file_contents=record_field_details_json) if len(modified_modules) > 0: for module in modified_modules.keys(): if module.lower() in record_field_details_json: Utility.delete_fields(record_field_details_json, module) Utility.write_to_file(file_path=record_field_details_path, file_contents=record_field_details_json) for module in modified_modules.keys(): module_data = modified_modules[module] Utility.get_fields_info(module_data[Constants.API_NAME])
def initialize_sdk(): # Create an instance of Logger Class that takes two parameters # 1 -> Level of the log messages to be logged. # Can be configured by typing Levels "." and choose any level from the list displayed. # 2 -> Absolute file path, where messages need to be logged. log_instance = Logger.get_instance(Logger.Levels.INFO, "/Users/Documents/new_logs.txt") # Create an UserSignature instance that takes user Email as parameter user = UserSignature("*****@*****.**") token = OAuthToken(client_id="clientId", client_secret="clientSecret", redirect_url="redirectURL", refresh_token="refresh token") # Configure the environment # which is of the pattern Domain.Environment # Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter # Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() environment = USDataCenter.PRODUCTION() # Create an instance of TokenStore """ Create an instance of TokenStore 1 -> Absolute file path of the file to persist tokens """ """ Create an instance of TokenStore 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" 6-> DataBase table_name . Default value "oauthtoken" """ store = DBStore(password="******") # tokens = store.get_token_by_id("python_abc.a_us_prd_c605",token) # store = FileStore('/Users/Documents/tokens.txt') # tokens = store.get_token_by_id("python_abc.a_us_prd_c605",token) """ A Boolean value for the key (auto_refresh_fields) to allow or prevent auto-refreshing of the modules' fields in the background. if true - all the modules' fields will be auto-refreshed in the background whenever there is any change. if false - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or the specific module's fields using methods from ModuleFieldsHandler """ config = SDKConfig(auto_refresh_fields=False, pick_list_validation=False, read_timeout=10.0, connect_timeout=10.0) """ The path containing the absolute directory path (in the key resource_path) to store user-specific files containing information about fields in modules. """ resource_path = '/Users/Documents' """ Call the static initialize method of Initializer class that takes the following arguments 1 -> UserSignature instance 2 -> Environment instance 3 -> Token instance 4 -> TokenStore instance 5 -> Logger instance 6 -> auto_refresh_fields 7 -> resource_path """ Initializer.initialize( user=user, environment=environment, token=token, # store=store) # sdk_config=config, # resource_path=resource_path, logger=log_instance)
def initialize(): """ Create an instance of Logger Class that takes two parameters 1 -> Level of the log messages to be logged. Can be configured by typing Logger.Levels "." and choose any level from the list displayed. 2 -> Absolute file path, where messages need to be logged. """ logger = Logger.get_instance( level=Logger.Levels.INFO, file_path= '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data/python_sdk_log.log' ) # Create an UserSignature instance that takes user Email as parameter user = UserSignature(email='*****@*****.**') """ Configure the environment which is of the pattern Domain.Environment Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() """ environment = USDataCenter.PRODUCTION() """ Create a Token instance that takes the following parameters 1 -> OAuth client id. 2 -> OAuth client secret. 3 -> REFRESH/GRANT token. 4 -> token type. 5 -> OAuth redirect URL. """ token = OAuthToken( client_id=os.getenv('zoho_client_id'), client_secret=os.getenv('zoho_client_secret'), token= '1000.e9b9a622cb83e2861be87787bb4f03ec.0ae31e6e956acd0dbb4a6c6780f4971b', token_type=TokenType.GRANT, redirect_url='https://www.brightermonday.co.ke') """ Create an instance of TokenStore 1 -> Absolute file path of the file to persist tokens """ store = FileStore( file_path= '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data/python_sdk_tokens.txt' ) """ Create an instance of TokenStore 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" """ # store = DBStore() # store = DBStore(host='host_name', database_name='database_name', user_name='user_name', password='******',port_number='port_number') """ auto_refresh_fields if True - all the modules' fields will be auto-refreshed in the background, every hour. if False - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(zcrmsdk/src/com/zoho/crm/api/util/module_fields_handler.py) pick_list_validation A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. if True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. if False - the SDK does not validate the input and makes the API request with the user’s input to the pick list """ config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) """ The path containing the absolute directory path (in the key resource_path) to store user-specific files containing information about fields in modules. """ resource_path = '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data' """ Create an instance of RequestProxy class that takes the following parameters 1 -> Host 2 -> Port Number 3 -> User Name. Default value is None 4 -> Password. Default value is None """ # request_proxy = RequestProxy(host='proxyHost', port=8080) # request_proxy = RequestProxy(host='proxyHost', port=8080, user='******', password='******') """ Call the static initialize method of Initializer class that takes the following arguments 1 -> UserSignature instance 2 -> Environment instance 3 -> Token instance 4 -> TokenStore instance 5 -> SDKConfig instance 6 -> resource_path 7 -> Logger instance. Default value is None 8 -> RequestProxy instance. Default value is None """ Initializer.initialize(user=user, environment=environment, token=token, store=store, sdk_config=config, resource_path=resource_path, logger=logger)
def api_call(self, class_name, encode_type): """ The method to construct API request and response details. To make the Zoho CRM API calls. Parameters: class_name(str): A str containing the method return type. encode_type(str): A str containing the expected API response content type. Returns: APIResponse: An instance of APIResponse representing the Zoho CRM API response instance Raises: SDKException """ try: from zcrmsdk.src.com.zoho.crm.api.initializer import Initializer except Exception: from ..initializer import Initializer if Initializer.get_initializer() is None: raise SDKException(code=Constants.SDK_UNINITIALIZATION_ERROR, message=Constants.SDK_UNINITIALIZATION_MESSAGE) connector = APIHTTPConnector() try: self.set_api_url(connector) except SDKException as e: CommonAPIHandler.logger.error(Constants.SET_API_URL_EXCEPTION + e.__str__()) raise e except Exception as e: sdk_exception = SDKException(cause=e) CommonAPIHandler.logger.error(Constants.SET_API_URL_EXCEPTION + sdk_exception.__str__()) raise sdk_exception connector.request_method = self.__http_method connector.content_type = self.__content_type if self.__header is not None and len( self.__header.request_headers) > 0: connector.headers = self.__header.request_headers if self.__param is not None and len( self.__param.request_parameters) > 0: connector.parameters = self.__param.request_parameters try: Initializer.get_initializer().token.authenticate(connector) except SDKException as e: CommonAPIHandler.logger.info(Constants.AUTHENTICATION_EXCEPTION + e.__str__()) raise e except Exception as e: sdk_exception = SDKException(cause=e) CommonAPIHandler.logger.error(Constants.AUTHENTICATION_EXCEPTION + sdk_exception.__str__()) raise sdk_exception convert_instance = None if self.__content_type is not None and self.__http_method in [ Constants.REQUEST_METHOD_PATCH, Constants.REQUEST_METHOD_POST, Constants.REQUEST_METHOD_PUT ]: try: convert_instance = self.get_converter_class_instance( self.__content_type.lower()) request = convert_instance.form_request( self.__request, self.__request.__class__.__module__, None, None) except SDKException as e: CommonAPIHandler.logger.info(Constants.FORM_REQUEST_EXCEPTION + e.__str__()) raise e except Exception as e: sdk_exception = SDKException(cause=e) CommonAPIHandler.logger.error( Constants.FORM_REQUEST_EXCEPTION + sdk_exception.__str__()) raise sdk_exception connector.request_body = request try: connector.headers[Constants.ZOHO_SDK] = platform.system( ) + "/" + platform.release( ) + " python/" + platform.python_version( ) + ":" + Constants.SDK_VERSION response = connector.fire_request(convert_instance) return_object = None if Constants.CONTENT_TYPE in response.headers: content_type = response.headers[Constants.CONTENT_TYPE] if ";" in content_type: content_type = content_type.rpartition(";")[0] convert_instance = self.get_converter_class_instance( str(content_type).lower()) return_object = convert_instance.get_wrapped_response( response, class_name) else: CommonAPIHandler.logger.info(response.__str__()) return APIResponse(response.headers, response.status_code, return_object) except SDKException as e: CommonAPIHandler.logger.info(Constants.API_CALL_EXCEPTION + e.__str__()) except Exception as e: sdk_exception = SDKException(cause=e) CommonAPIHandler.logger.error(Constants.API_CALL_EXCEPTION + sdk_exception.__str__()) raise sdk_exception
def get_custom_views(module_api_name): """ Create an instance of Logger Class that takes two parameters 1 -> Level of the log messages to be logged. Can be configured by typing Logger.Levels "." and choose any level from the list displayed. 2 -> Absolute file path, where messages need to be logged. """ logger = Logger.get_instance( level=Logger.Levels.INFO, file_path= '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data/python_sdk_log.log' ) # Create an UserSignature instance that takes user Email as parameter user = UserSignature(email='*****@*****.**') """ Configure the environment which is of the pattern Domain.Environment Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() """ environment = USDataCenter.PRODUCTION() """ Create a Token instance that takes the following parameters 1 -> OAuth client id. 2 -> OAuth client secret. 3 -> REFRESH/GRANT token. 4 -> token type. 5 -> OAuth redirect URL. """ token = OAuthToken( client_id=os.getenv('zoho_client_id'), client_secret=os.getenv('zoho_client_secret'), token= '1000.4ceee886d212fe2f4bae575841b2d9d1.8716ba1d1d064921e67612fce4a1cc5b', token_type=TokenType.GRANT, redirect_url='https://www.brightermonday.co.ke') """ Create an instance of TokenStore 1 -> Absolute file path of the file to persist tokens """ store = FileStore( file_path= '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data/python_sdk_tokens.txt' ) """ Create an instance of TokenStore 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" """ # store = DBStore() # store = DBStore(host='host_name', database_name='database_name', user_name='user_name', password='******',port_number='port_number') """ auto_refresh_fields if True - all the modules' fields will be auto-refreshed in the background, every hour. if False - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(zcrmsdk/src/com/zoho/crm/api/util/module_fields_handler.py) pick_list_validation A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. if True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. if False - the SDK does not validate the input and makes the API request with the user’s input to the pick list """ config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) """ The path containing the absolute directory path (in the key resource_path) to store user-specific files containing information about fields in modules. """ resource_path = '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data' """ Create an instance of RequestProxy class that takes the following parameters 1 -> Host 2 -> Port Number 3 -> User Name. Default value is None 4 -> Password. Default value is None """ # request_proxy = RequestProxy(host='proxyHost', port=8080) # request_proxy = RequestProxy(host='proxyHost', port=8080, user='******', password='******') """ Call the static initialize method of Initializer class that takes the following arguments 1 -> UserSignature instance 2 -> Environment instance 3 -> Token instance 4 -> TokenStore instance 5 -> SDKConfig instance 6 -> resource_path 7 -> Logger instance. Default value is None 8 -> RequestProxy instance. Default value is None """ Initializer.initialize(user=user, environment=environment, token=token, store=store, sdk_config=config, resource_path=resource_path, logger=logger) """ This method is used to get the custom views data of a particular module. Specify the module name in your API request whose custom view data you want to retrieve. :param module_api_name: the API name of the required module. """ """ example module_api_name = "Leads"; """ # Get instance of CustomViewOperations Class that takes module_api_name as parameter custom_views_operations = CustomViewsOperations(module_api_name) # Get instance of ParameterMap Class param_instance = ParameterMap() # Possible parameters of Get CustomViews operation param_instance.add(GetCustomViewsParam.page, 1) param_instance.add(GetCustomViewsParam.per_page, 20) # Call get_custom_views method that takes ParameterMap instance as parameter response = custom_views_operations.get_custom_views(param_instance) if response is not None: # Get the status code from response print('Status Code: ' + str(response.get_status_code())) if response.get_status_code() in [204, 304]: print('No Content' if response.get_status_code() == 204 else 'Not Modified') return # Get object from response response_object = response.get_object() if response_object is not None: # Check if expected ResponseWrapper instance is received if isinstance(response_object, ResponseWrapper): # Get the list of obtained CustomView instances custom_views_list = response_object.get_custom_views() for custom_view in custom_views_list: # Get the ID of each CustomView print('CustomView ID: ' + str(custom_view.get_id())) # Get the Name of each CustomView print('CustomView Name: ' + str(custom_view.get_name())) # Get the System Name of each CustomView print('CustomView System Name: ' + str(custom_view.get_system_name())) # Get the Category of each CustomView print('CustomView Category: ' + str(custom_view.get_category())) # Get the DisplayValue of each CustomView print('CustomView Display Value: ' + str(custom_view.get_display_value())) # Get the Offline value of each CustomView print('CustomView Is offline: ' + str(custom_view.get_offline())) # Get the default value of each CustomView print('CustomView Is default: ' + str(custom_view.get_default())) # Get the SystemDefined of each CustomView print('CustomView Is System Defined: ' + str(custom_view.get_system_defined())) if custom_view.get_favorite() is not None: # Get the Favorite of each CustomView print('CustomView Favorite: ' + str(custom_view.get_favorite())) info = response_object.get_info() if info is not None: print("CustomView Info") if info.get_per_page() is not None: # Get the PerPage from Info print('PerPage: ' + str(info.get_per_page())) if info.get_page() is not None: # Get the Page from Info print('Page: ' + str(info.get_page())) if info.get_more_records() is not None: # Get the MoreRecords from Info print('MoreRecords: ' + str(info.get_more_records())) if info.get_default() is not None: # Get the Default from Info print('Default: ' + info.get_default()) if info.get_count() is not None: # Get the Count from Info print('Count: ' + str(info.get_count())) translation = info.get_translation() if translation is not None: print("Translation details") # Get the PublicViews of the Translation print('PublicViews: ' + translation.get_public_views()) # Get the OtherUsersViews of the Translation print('OtherUsersViews: ' + translation.get_other_users_views()) # Get the SharedWithMe of the Translation print('SharedWithMe: ' + translation.get_shared_with_me()) # Get the CreatedByMe of the Translation print('CreatedByMe: ' + translation.get_created_by_me()) # Check if the request returned an exception elif isinstance(response_object, APIException): # Get the Status print("Status: " + response_object.get_status().get_value()) # Get the Code print("Code: " + response_object.get_code().get_value()) print("Details") # Get the details dict details = response_object.get_details() for key, value in details.items(): print(key + ' : ' + str(value)) # Get the Message print("Message: " + response_object.get_message().get_value())
def fire_request(self, converter_instance): """ This method makes a request to the Zoho CRM Rest API Parameters: converter_instance (Converter) : A Converter class instance to call append_to_request method. Returns: requests.Response : An object of requests.Response """ response = None proxies = None logger = logging.getLogger('SDKLogger') if self.content_type is not None: self.set_content_type_header() if Initializer.get_initializer().request_proxy is not None: request_proxy = Initializer.get_initializer().request_proxy auth = "" if request_proxy.user is not None: auth = request_proxy.user + ':' + request_proxy.password + '@' if Constants.HTTP in request_proxy.host: host_split = request_proxy.host.split('://') scheme = host_split[0] proxies = { scheme: scheme + '://' + auth + host_split[1] + ':' + str(request_proxy.port) } else: proxies = { Constants.HTTP: Constants.HTTP + '://' + auth + request_proxy.host + ':' + str(request_proxy.port), Constants.HTTPS: Constants.HTTPS + '://' + auth + request_proxy.host + ':' + str(request_proxy.port) } logger.info(self.proxy_log(request_proxy)) logger.info(self.__str__()) if self.request_method == Constants.REQUEST_METHOD_GET: response = requests.get(url=self.url, headers=self.headers, params=self.parameters, allow_redirects=False, proxies=proxies) elif self.request_method == Constants.REQUEST_METHOD_PUT: data = None if self.request_body is not None: data = converter_instance.append_to_request(self, self.request_body) response = requests.put(url=self.url, data=data, params=self.parameters, headers=self.headers, allow_redirects=False, proxies=proxies) elif self.request_method == Constants.REQUEST_METHOD_POST: data = None if self.request_body is not None: data = converter_instance.append_to_request(self, self.request_body) if self.file: response = requests.post(url=self.url, files=data, headers=self.headers, allow_redirects=False, data={}, proxies=proxies) else: response = requests.post(url=self.url, data=data, params=self.parameters, headers=self.headers, allow_redirects=False, proxies=proxies) elif self.request_method == Constants.REQUEST_METHOD_PATCH: data = None if self.request_body is not None: data = converter_instance.append_to_request(self, self.request_body) response = requests.patch(url=self.url, data=data, headers=self.headers, params=self.parameters, allow_redirects=False, proxies=proxies) elif self.request_method == Constants.REQUEST_METHOD_DELETE: response = requests.delete(url=self.url, headers=self.headers, params=self.parameters, allow_redirects=False, proxies=proxies) return response
def download_result(job_id, destination_folder): """ Create an instance of Logger Class that takes two parameters 1 -> Level of the log messages to be logged. Can be configured by typing Logger.Levels "." and choose any level from the list displayed. 2 -> Absolute file path, where messages need to be logged. """ logger = Logger.get_instance( level=Logger.Levels.INFO, file_path= '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data/python_sdk_log.log' ) # Create an UserSignature instance that takes user Email as parameter user = UserSignature(email='*****@*****.**') """ Configure the environment which is of the pattern Domain.Environment Available Domains: USDataCenter, EUDataCenter, INDataCenter, CNDataCenter, AUDataCenter Available Environments: PRODUCTION(), DEVELOPER(), SANDBOX() """ environment = USDataCenter.PRODUCTION() """ Create a Token instance that takes the following parameters 1 -> OAuth client id. 2 -> OAuth client secret. 3 -> REFRESH/GRANT token. 4 -> token type. 5 -> OAuth redirect URL. """ token = OAuthToken( client_id=os.getenv('zoho_client_id'), client_secret=os.getenv('zoho_client_secret'), token= '1000.e9b9a622cb83e2861be87787bb4f03ec.0ae31e6e956acd0dbb4a6c6780f4971b', token_type=TokenType.GRANT, redirect_url='https://www.brightermonday.co.ke') """ Create an instance of TokenStore 1 -> Absolute file path of the file to persist tokens """ store = FileStore( file_path= '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data/python_sdk_tokens.txt' ) """ Create an instance of TokenStore 1 -> DataBase host name. Default value "localhost" 2 -> DataBase name. Default value "zohooauth" 3 -> DataBase user name. Default value "root" 4 -> DataBase password. Default value "" 5 -> DataBase port number. Default value "3306" """ # store = DBStore() # store = DBStore(host='host_name', database_name='database_name', user_name='user_name', password='******',port_number='port_number') """ auto_refresh_fields if True - all the modules' fields will be auto-refreshed in the background, every hour. if False - the fields will not be auto-refreshed in the background. The user can manually delete the file(s) or refresh the fields using methods from ModuleFieldsHandler(zcrmsdk/src/com/zoho/crm/api/util/module_fields_handler.py) pick_list_validation A boolean field that validates user input for a pick list field and allows or disallows the addition of a new value to the list. if True - the SDK validates the input. If the value does not exist in the pick list, the SDK throws an error. if False - the SDK does not validate the input and makes the API request with the user’s input to the pick list """ config = SDKConfig(auto_refresh_fields=True, pick_list_validation=False) """ The path containing the absolute directory path (in the key resource_path) to store user-specific files containing information about fields in modules. """ resource_path = '/home/simon/commerce_cube/ecom-ds-PropensityReporting/data' """ Create an instance of RequestProxy class that takes the following parameters 1 -> Host 2 -> Port Number 3 -> User Name. Default value is None 4 -> Password. Default value is None """ # request_proxy = RequestProxy(host='proxyHost', port=8080) # request_proxy = RequestProxy(host='proxyHost', port=8080, user='******', password='******') """ Call the static initialize method of Initializer class that takes the following arguments 1 -> UserSignature instance 2 -> Environment instance 3 -> Token instance 4 -> TokenStore instance 5 -> SDKConfig instance 6 -> resource_path 7 -> Logger instance. Default value is None 8 -> RequestProxy instance. Default value is None """ Initializer.initialize(user=user, environment=environment, token=token, store=store, sdk_config=config, resource_path=resource_path, logger=logger) """ This method is used to download the result of Bulk Read operation :param job_id: The unique ID of the bulk read job. :param destination_folder: The absolute path where downloaded file has to be stored. """ """ example job_id = 3409643000002461001 """ # Get instance of BulkReadOperations Class bulk_read_operations = BulkReadOperations() # Call download_result method that takes job_id as parameter response = bulk_read_operations.download_result(job_id) if response is not None: # Get the status code from response print('Status Code: ' + str(response.get_status_code())) if response.get_status_code() in [204, 304]: print('No Content' if response.get_status_code() == 204 else 'Not Modified') return # Get object from response response_object = response.get_object() if response_object is not None: # Check if expected FileBodyWrapper instance is received. if isinstance(response_object, FileBodyWrapper): # Get StreamWrapper instance from the returned FileBodyWrapper instance stream_wrapper = response_object.get_file() # Construct the file name by joining the destinationFolder and the name from StreamWrapper instance file_name = os.path.join(destination_folder, stream_wrapper.get_name()) # Open the destination file where the file needs to be written in 'wb' mode with open(file_name, 'wb') as f: # Get the stream from StreamWrapper instance for chunk in stream_wrapper.get_stream(): f.write(chunk) f.close() # Check if the request returned an exception elif isinstance(response_object, APIException): # Get the Status print("Status: " + response_object.get_status().get_value()) # Get the Code print("Code: " + response_object.get_code().get_value()) print("Details") # Get the details dict details = response_object.get_details() for key, value in details.items(): print(key + ' : ' + str(value)) # Get the Message print("Message: " + response_object.get_message().get_value())