def ip(field_rules, field_value): ip_libraries = { # Set the key to the name of the module to import. # The value will be a dictionary with three keys: # # - function: The object or function to call, passing the IP # address as the first argument. # # - event: If the library in question throws an exception when # passed an invalid IP address, set to "exception". If the # library returns a specific value when passed an invalid IP, # set to "value". # # - action: If "event" is set to "exception", specify the # exception class here, NOT as a string. If "event" is set to # "value", specify the value to look for/compare against. # # If the value specified is encountered or if the exception # specified is thrown, validation fails. Otherwise, validation # succeeds. 'ipaddress': { 'function': 'ip_address', 'event': 'exception', 'action': ValueError, }, 'ipaddr': { 'function': 'IPAddress', 'event': 'exception', 'action': ValueError, }, 'IPy': { 'function': 'IP', 'event': 'exception', 'action': ValueError, }, } for ip_library, ip_config in compatibility.iterdict(ip_libraries): try: ip_handler = __import__(ip_library) try: # Grab the function we're going to call. ip_function = getattr(ip_handler, '{function}'.format(function=ip_config['function'])) # Call the function passing the IP as an argument. ip_result = ip_function(field_value) if ip_config['event'] == 'exception' or (ip_config['event'] == 'compare' and ip_result == ip_config['action']): return True except ip_config['action'] as e: # IP module exists, but the IP address isn't valid. # Break the iteration, and return None. return None except ImportError as e: # Error importing module try another one (if there is one) continue return True
def add_fields(self, fields): for field_name, field_value in compatibility.iterdict(fields): self.add_field(field_name, field_value)
def _request_arguments(self): arguments = {} for field_name, field_value in compatibility.iterdict(self.fields): argument = fields.rules[field_name]["arg"] arguments[argument] = field_value return compatibility.urlencode(arguments)