Browse Source

After pylint

prieto 8 years ago
parent
commit
a1afe3b48d
3 changed files with 153 additions and 210 deletions
  1. 2
    1
      lodel/mlnamedobject/mlnamedobject.py
  2. 51
    58
      lodel/settings/settings_loader.py
  3. 100
    151
      lodel/validator/validator.py

+ 2
- 1
lodel/mlnamedobject/mlnamedobject.py View File

8
 #
8
 #
9
 # Display name and Description of a lodel2 object
9
 # Display name and Description of a lodel2 object
10
 
10
 
11
+##@brief Class allows dislpay name and help text for lodel2 objects and fields
11
 class MlNamedObject(object):
12
 class MlNamedObject(object):
12
 
13
 
13
-    def __init__(self, display_name = None, help_text = None, toto=None):
14
+    def __init__(self, display_name=None, help_text=None):
14
         self.display_name = None if display_name is None else MlString(display_name)
15
         self.display_name = None if display_name is None else MlString(display_name)
15
         self.help_text = None if help_text is None else MlString(help_text)
16
         self.help_text = None if help_text is None else MlString(help_text)

+ 51
- 58
lodel/settings/settings_loader.py View File

13
 
13
 
14
 ##@brief Merges and loads configuration files
14
 ##@brief Merges and loads configuration files
15
 class SettingsLoader(object):
15
 class SettingsLoader(object):
16
-    
16
+
17
     ## To avoid the DEFAULT section whose values are found in all sections, we
17
     ## To avoid the DEFAULT section whose values are found in all sections, we
18
     # have to give it an unsual name
18
     # have to give it an unsual name
19
     DEFAULT_SECTION = 'lodel2_default_passaway_tip'
19
     DEFAULT_SECTION = 'lodel2_default_passaway_tip'
20
-    
20
+
21
     ## @brief Virtual filename when default value is used
21
     ## @brief Virtual filename when default value is used
22
     DEFAULT_FILENAME = 'default_value'
22
     DEFAULT_FILENAME = 'default_value'
23
 
23
 
24
     ##@brief Constructor
24
     ##@brief Constructor
25
     # @param conf_path str : conf.d path
25
     # @param conf_path str : conf.d path
26
-    def __init__(self,conf_path):
27
-        self.__conf_path=conf_path
28
-        self.__conf_sv=dict()
29
-        self.__conf=self.__merge()
26
+    def __init__(self, conf_path):
27
+        self.__conf_path = conf_path
28
+        self.__conf_sv = dict()
29
+        self.__conf = self.__merge()
30
         # Stores errors
30
         # Stores errors
31
         self.__errors_list = []
31
         self.__errors_list = []
32
-    
32
+
33
     ##@brief Lists and merges files in settings_loader.conf_path
33
     ##@brief Lists and merges files in settings_loader.conf_path
34
     # @return dict()
34
     # @return dict()
35
     def __merge(self):
35
     def __merge(self):
38
         logger.debug("SettingsLoader found those settings files : %s" % (
38
         logger.debug("SettingsLoader found those settings files : %s" % (
39
             ', '.join(l_dir)))
39
             ', '.join(l_dir)))
40
 
40
 
41
-        for f_ini in l_dir:  
42
-            config = configparser.ConfigParser(default_section = self.DEFAULT_SECTION ,interpolation=None)
41
+        for f_ini in l_dir:
42
+            config = configparser.ConfigParser(default_section=self.DEFAULT_SECTION, interpolation=None)
43
             config.read(f_ini)
43
             config.read(f_ini)
44
-            for section in [ s for s in config if s != self.DEFAULT_SECTION ]:
44
+            for section in [s for s in config if s != self.DEFAULT_SECTION]:
45
                 if section not in conf:
45
                 if section not in conf:
46
                     conf[section] = dict()
46
                     conf[section] = dict()
47
                 for param in config[section]:
47
                 for param in config[section]:
48
-                    if param not in conf[section]: 
49
-                        conf[section][param]=dict()
48
+                    if param not in conf[section]:
49
+                        conf[section][param] = dict()
50
                         conf[section][param]['value'] = config[section][param]
50
                         conf[section][param]['value'] = config[section][param]
51
                         conf[section][param]['file'] = f_ini
51
                         conf[section][param]['file'] = f_ini
52
-                        self.__conf_sv[section + ':' + param]=f_ini
52
+                        self.__conf_sv[section + ':' + param] = f_ini
53
                     else:
53
                     else:
54
-                        raise SettingsError("Error redeclaration of key %s in section %s. Found in %s and %s" % (
55
-            section,
56
-            param,
57
-            f_ini,
58
-            conf[section][param]['file']))
54
+                        raise SettingsError("Error redeclaration of key %s \
55
+                            in section %s. Found in %s and %s" % (\
56
+                            section, param, f_ini, conf[section][param]['file']))
59
         return conf
57
         return conf
60
-    
58
+
61
     ##@brief Returns option if exists default_value else and validates
59
     ##@brief Returns option if exists default_value else and validates
62
     # @param section str : name of the section
60
     # @param section str : name of the section
63
     # @param keyname str
61
     # @param keyname str
65
     # @param default_value *
63
     # @param default_value *
66
     # @param mandatory bool
64
     # @param mandatory bool
67
     # @return the option
65
     # @return the option
68
-    def getoption(self,section,keyname,validator,default_value=None,mandatory=False):
69
-        conf=self.__conf
66
+    def getoption(self, section, keyname, validator, default_value=None, mandatory=False):
67
+        conf = self.__conf
70
         if section not in conf:
68
         if section not in conf:
71
             conf[section] = dict()
69
             conf[section] = dict()
72
 
70
 
85
         if result is None:
83
         if result is None:
86
             if default_value is None and mandatory:
84
             if default_value is None and mandatory:
87
                 msg = "Default value mandatory for option %s" % keyname
85
                 msg = "Default value mandatory for option %s" % keyname
88
-                expt = SettingsError(   msg = msg,
89
-                                        key_id = section+'.'+keyname,
90
-                                        filename = sec[keyname]['file'])
86
+                expt = SettingsError(msg=msg, key_id=section+'.'+keyname, \
87
+                    filename=sec[keyname]['file'])
91
                 self.__errors_list.append(expt)
88
                 self.__errors_list.append(expt)
92
                 return
89
                 return
93
             else:
90
             else:
94
-                sec[keyname]=dict()
91
+                sec[keyname] = dict()
95
                 sec[keyname]['value'] = default_value
92
                 sec[keyname]['value'] = default_value
96
                 sec[keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
93
                 sec[keyname]['file'] = SettingsLoader.DEFAULT_FILENAME
97
                 result = default_value
94
                 result = default_value
98
-                logger.debug("Using default value for configuration key %s:%s" % (
99
-                    section, keyname))
95
+                logger.debug("Using default value for configuration key %s:%s" \
96
+                    % (section, keyname))
100
 
97
 
101
         try:
98
         try:
102
             return validator(result)
99
             return validator(result)
103
         except Exception as e:
100
         except Exception as e:
104
             # Generating nice exceptions
101
             # Generating nice exceptions
105
             if False and sec[keyname]['file'] == SettingsLoader.DEFAULT_FILENAME:
102
             if False and sec[keyname]['file'] == SettingsLoader.DEFAULT_FILENAME:
106
-                expt = SettingsError(   msg = 'Mandatory settings not found',
107
-                                        key_id = section+'.'+keyname)
103
+                expt = SettingsError(msg='Mandatory settings not found', \
104
+                                    key_id=section+'.'+keyname)
108
                 self.__errors_list.append(expt)
105
                 self.__errors_list.append(expt)
109
             else:
106
             else:
110
-                expt = ValidationError(
111
-                                                "For %s.%s : %s" % 
112
-                                                (section, keyname,e)
113
-                )
114
-                expt2 = SettingsError(  msg = str(expt),
115
-                                        key_id = section+'.'+keyname,
116
-                                        filename = sec[keyname]['file'])
107
+                expt = ValidationError("For %s.%s : %s" % (section, keyname, e))
108
+                expt2 = SettingsError(msg=str(expt), \
109
+                                        key_id=section+'.'+keyname, \
110
+                                        filename=sec[keyname]['file'])
117
                 self.__errors_list.append(expt2)
111
                 self.__errors_list.append(expt2)
118
             return
112
             return
119
 
113
 
123
     # @param value str
117
     # @param value str
124
     # @param validator callable : takes one argument value and raises validation fail
118
     # @param validator callable : takes one argument value and raises validation fail
125
     # @return the option
119
     # @return the option
126
-    def setoption(self,section,keyname,value,validator):
127
-        f_conf=copy.copy(self.__conf[section][keyname]['file'])
120
+    def setoption(self, section, keyname, value, validator):
121
+        f_conf = copy.copy(self.__conf[section][keyname]['file'])
128
         if f_conf == SettingsLoader.DEFAULT_FILENAME:
122
         if f_conf == SettingsLoader.DEFAULT_FILENAME:
129
             f_conf = self.__conf_path + '/generated.ini'
123
             f_conf = self.__conf_path + '/generated.ini'
130
 
124
 
131
-        conf=self.__conf
125
+        conf = self.__conf
132
         conf[section][keyname] = value
126
         conf[section][keyname] = value
133
         config = configparser.ConfigParser()
127
         config = configparser.ConfigParser()
134
         config.read(f_conf)
128
         config.read(f_conf)
135
         if section not in config:
129
         if section not in config:
136
-            config[section]={}
130
+            config[section] = {}
137
         config[section][keyname] = validator(value)
131
         config[section][keyname] = validator(value)
138
-        
132
+
139
         with open(f_conf, 'w') as configfile:
133
         with open(f_conf, 'w') as configfile:
140
             config.write(configfile)
134
             config.write(configfile)
141
-            
135
+
142
     ##@brief Saves new partial configuration. Writes in the conf files corresponding
136
     ##@brief Saves new partial configuration. Writes in the conf files corresponding
143
     # @param sections dict
137
     # @param sections dict
144
     # @param validators dict of callable : takes one argument value and raises validation fail
138
     # @param validators dict of callable : takes one argument value and raises validation fail
145
     def saveconf(self, sections, validators):
139
     def saveconf(self, sections, validators):
146
         for sec in sections:
140
         for sec in sections:
147
             for kname in sections[sec]:
141
             for kname in sections[sec]:
148
-                self.setoption(sec,kname,sections[sec][kname],validators[sec][kname])
149
-    
142
+                self.setoption(sec, kname, sections[sec][kname], validators[sec][kname])
143
+
150
     ##@brief Returns the section to be configured
144
     ##@brief Returns the section to be configured
151
     # @param section_prefix str
145
     # @param section_prefix str
152
     # @param default_section str
146
     # @param default_section str
153
     # @return the section as dict()
147
     # @return the section as dict()
154
-    def getsection(self,section_prefix,default_section=None):
155
-        conf=copy.copy(self.__conf)
156
-       
157
-        sections=[]
148
+    def getsection(self, section_prefix, default_section=None):
149
+        conf = copy.copy(self.__conf)
150
+
151
+        sections = []
158
         if section_prefix in conf:
152
         if section_prefix in conf:
159
             sections.append(section_prefix)
153
             sections.append(section_prefix)
160
         for sect_names in conf:
154
         for sect_names in conf:
162
                 pass
156
                 pass
163
             elif sect_names.startswith(section_prefix + '.'):
157
             elif sect_names.startswith(section_prefix + '.'):
164
                 sections.append(sect_names)
158
                 sections.append(sect_names)
165
-        if sections == [] and default_section: 
166
-             sections.append(section_prefix + '.' + default_section)
159
+        if sections == [] and default_section:
160
+            sections.append(section_prefix + '.' + default_section)
167
         elif sections == []:
161
         elif sections == []:
168
             raise NameError("Not existing settings section : %s" % section_prefix)
162
             raise NameError("Not existing settings section : %s" % section_prefix)
169
-            
163
+
170
         return sections
164
         return sections
171
-    
165
+
172
     ##@brief Returns invalid settings
166
     ##@brief Returns invalid settings
173
     #
167
     #
174
-    # This method returns all the settings that was not fecthed by 
168
+    # This method returns all the settings that was not fecthed by
175
     # getsection() method. For the Settings object it allows to know
169
     # getsection() method. For the Settings object it allows to know
176
     # the list of invalids settings keys
170
     # the list of invalids settings keys
177
     # @return a dict with SECTION_NAME+":"+KEY_NAME as key and the filename
171
     # @return a dict with SECTION_NAME+":"+KEY_NAME as key and the filename
178
     # where the settings was found as value
172
     # where the settings was found as value
179
     def getremains(self):
173
     def getremains(self):
180
         return self.__conf_sv
174
         return self.__conf_sv
181
-    
175
+
182
     ##@brief Raise a SettingsErrors exception if some confs remains
176
     ##@brief Raise a SettingsErrors exception if some confs remains
183
     #@note typically used at the end of Settings bootstrap
177
     #@note typically used at the end of Settings bootstrap
184
     def raise_errors(self):
178
     def raise_errors(self):
185
         remains = self.getremains()
179
         remains = self.getremains()
186
         err_l = self.__errors_list
180
         err_l = self.__errors_list
187
         for key_id, filename in remains.items():
181
         for key_id, filename in remains.items():
188
-            err_l.append(SettingsError( msg = "Invalid configuration key",
189
-                                        key_id = key_id,
190
-                                        filename = filename))
182
+            err_l.append(SettingsError(msg="Invalid configuration key", \
183
+                                    key_id=key_id, \
184
+                                    filename=filename))
191
         if len(err_l) > 0:
185
         if len(err_l) > 0:
192
             raise SettingsErrors(err_l)
186
             raise SettingsErrors(err_l)
193
         else:
187
         else:
194
             return
188
             return
195
-

+ 100
- 151
lodel/validator/validator.py View File

11
 LodelContext.expose_modules(globals(), {
11
 LodelContext.expose_modules(globals(), {
12
     'lodel.mlnamedobject.mlnamedobject': ['MlNamedObject'],
12
     'lodel.mlnamedobject.mlnamedobject': ['MlNamedObject'],
13
     'lodel.exceptions': ['LodelException', 'LodelExceptions',
13
     'lodel.exceptions': ['LodelException', 'LodelExceptions',
14
-        'LodelFatalError', 'FieldValidationError']})
14
+    'LodelFatalError', 'FieldValidationError']})
15
 
15
 
16
 ## @package lodel.settings.validator Lodel2 settings validators/cast module
16
 ## @package lodel.settings.validator Lodel2 settings validators/cast module
17
 #
17
 #
30
 # casted value.
30
 # casted value.
31
 #@todo implement an IP validator and use it in multisite confspec
31
 #@todo implement an IP validator and use it in multisite confspec
32
 class Validator(MlNamedObject):
32
 class Validator(MlNamedObject):
33
-    
33
+
34
     _validators = dict()
34
     _validators = dict()
35
     _description = dict()
35
     _description = dict()
36
-    
36
+
37
     ##@brief Instanciate a validator
37
     ##@brief Instanciate a validator
38
     #@param name str : validator name
38
     #@param name str : validator name
39
     #@param none_is_valid bool : if True None will be validated
39
     #@param none_is_valid bool : if True None will be validated
40
     #@param **kwargs : more arguement for the validator
40
     #@param **kwargs : more arguement for the validator
41
-    def __init__(self, name, none_is_valid = False, display_name = None, help_text = None, **kwargs):
41
+    def __init__(self, name, none_is_valid=False, display_name=None, help_text=None, **kwargs):
42
         if name is not None and name not in self._validators:
42
         if name is not None and name not in self._validators:
43
             raise LodelFatalError("No validator named '%s'" % name)
43
             raise LodelFatalError("No validator named '%s'" % name)
44
         self.__none_is_valid = none_is_valid
44
         self.__none_is_valid = none_is_valid
58
         try:
58
         try:
59
             ret = self._validators[self.__name](value, **self._opt_args)
59
             ret = self._validators[self.__name](value, **self._opt_args)
60
             return ret
60
             return ret
61
-        except Exception as e:
62
-            raise ValidationError(e)
63
-    
61
+        except Exception as exp:
62
+            raise ValidationError(exp)
63
+
64
     ##@brief Register a new validator
64
     ##@brief Register a new validator
65
     # @param name str : validator name
65
     # @param name str : validator name
66
     # @param callback callable : the function that will validate a value
66
     # @param callback callable : the function that will validate a value
74
             raise TypeError("Callable expected but got %s" % type(callback))
74
             raise TypeError("Callable expected but got %s" % type(callback))
75
         cls._validators[name] = callback
75
         cls._validators[name] = callback
76
         cls._description[name] = description
76
         cls._description[name] = description
77
-    
77
+
78
     ##@brief Get the validator list associated with description
78
     ##@brief Get the validator list associated with description
79
     @classmethod
79
     @classmethod
80
     def validators_list(cls):
80
     def validators_list(cls):
87
     # @param separator str : The element separator
87
     # @param separator str : The element separator
88
     # @return A Validator instance
88
     # @return A Validator instance
89
     @classmethod
89
     @classmethod
90
-    def create_list_validator(cls, validator_name, elt_validator, description = None, separator = ','):
90
+    def create_list_validator(cls, validator_name, elt_validator, description=None, separator=','):
91
         def list_validator(value):
91
         def list_validator(value):
92
             res = list()
92
             res = list()
93
-            errors = list()
94
             for elt in value.split(separator):
93
             for elt in value.split(separator):
95
                 elt = elt_validator(elt)
94
                 elt = elt_validator(elt)
96
                 if len(elt) > 0:
95
                 if len(elt) > 0:
97
                     res.append(elt)
96
                     res.append(elt)
98
             return res
97
             return res
99
         description = "Convert value to an array" if description is None else description
98
         description = "Convert value to an array" if description is None else description
100
-        cls.register_validator(
101
-                                validator_name,
102
-                                list_validator,
103
-                                description)
99
+        cls.register_validator(validator_name, list_validator, description)
104
         return cls(validator_name)
100
         return cls(validator_name)
105
- 
101
+
106
     ##@brief Create and register a list validator which reads an array and returns a string
102
     ##@brief Create and register a list validator which reads an array and returns a string
107
     # @param elt_validator callable : The validator that will be used for validate each elt value
103
     # @param elt_validator callable : The validator that will be used for validate each elt value
108
     # @param validator_name str
104
     # @param validator_name str
110
     # @param separator str : The element separator
106
     # @param separator str : The element separator
111
     # @return A Validator instance
107
     # @return A Validator instance
112
     @classmethod
108
     @classmethod
113
-    def create_write_list_validator(cls, validator_name, elt_validator, description = None, separator = ','):
109
+    def create_write_list_validator(cls, validator_name, elt_validator, description=None, separator=','):
114
         def write_list_validator(value):
110
         def write_list_validator(value):
115
             res = ''
111
             res = ''
116
-            errors = list()
117
             for elt in value:
112
             for elt in value:
118
                 res += elt_validator(elt) + ','
113
                 res += elt_validator(elt) + ','
119
             return res[:len(res)-1]
114
             return res[:len(res)-1]
120
         description = "Convert value to a string" if description is None else description
115
         description = "Convert value to a string" if description is None else description
121
-        cls.register_validator(
122
-                                validator_name,
123
-                                write_list_validator,
124
-                                description)
116
+        cls.register_validator(validator_name, write_list_validator, description)
125
         return cls(validator_name)
117
         return cls(validator_name)
126
-    
118
+
127
     ##@brief Create and register a regular expression validator
119
     ##@brief Create and register a regular expression validator
128
     # @param pattern str : regex pattern
120
     # @param pattern str : regex pattern
129
     # @param validator_name str : The validator name
121
     # @param validator_name str : The validator name
130
     # @param description str : Validator description
122
     # @param description str : Validator description
131
     # @return a Validator instance
123
     # @return a Validator instance
132
     @classmethod
124
     @classmethod
133
-    def create_re_validator(cls, pattern, validator_name, description = None):
125
+    def create_re_validator(cls, pattern, validator_name, description=None):
134
         def re_validator(value):
126
         def re_validator(value):
135
             if not re.match(pattern, value):
127
             if not re.match(pattern, value):
136
-                raise ValidationError("The value '%s' doesn't match the following pattern '%s'" % pattern)
128
+                raise ValidationError(\
129
+                    "The value '%s' doesn't match the following pattern '%s'" \
130
+                    % pattern)
137
             return value
131
             return value
138
         #registering the validator
132
         #registering the validator
139
-        cls.register_validator(
140
-                                validator_name,
141
-                                re_validator,
142
-                                ("Match value to '%s'" % pattern) if description is None else description)
133
+        cls.register_validator(validator_name, re_validator, \
134
+            ("Match value to '%s'" % pattern) \
135
+            if description is None else description)
143
         return cls(validator_name)
136
         return cls(validator_name)
144
 
137
 
145
-    
146
     ## @return a list of registered validators
138
     ## @return a list of registered validators
147
     @classmethod
139
     @classmethod
148
     def validators_list_str(cls):
140
     def validators_list_str(cls):
183
 def directory_val(value):
175
 def directory_val(value):
184
     res = Validator('strip')(value)
176
     res = Validator('strip')(value)
185
     if not os.path.isdir(res):
177
     if not os.path.isdir(res):
186
-        raise ValidationError("Folowing path don't exists or is not a directory : '%s'"%res)
178
+        raise ValidationError("Following path don't exists or is not a directory : '%s'"%res)
187
     return res
179
     return res
188
 
180
 
189
 ##@brief Validate a loglevel value
181
 ##@brief Validate a loglevel value
190
 def loglevel_val(value):
182
 def loglevel_val(value):
191
     valids = ['DEBUG', 'INFO', 'WARNING', 'SECURITY', 'ERROR', 'CRITICAL']
183
     valids = ['DEBUG', 'INFO', 'WARNING', 'SECURITY', 'ERROR', 'CRITICAL']
192
     if value.upper() not in valids:
184
     if value.upper() not in valids:
193
-        raise ValidationError(
194
-                "The value '%s' is not a valid loglevel" % value)
185
+        raise ValidationError( \
186
+            "The value '%s' is not a valid loglevel" % value)
195
     return value.upper()
187
     return value.upper()
196
 
188
 
197
 ##@brief Validate a path
189
 ##@brief Validate a path
198
 def path_val(value):
190
 def path_val(value):
199
     if value is None or not os.path.exists(value):
191
     if value is None or not os.path.exists(value):
200
-        raise ValidationError(
201
-                "path '%s' doesn't exists" % value)
192
+        raise ValidationError( \
193
+            "path '%s' doesn't exists" % value)
202
     return value
194
     return value
203
 
195
 
204
 ##@brief Validate None
196
 ##@brief Validate None
211
 def str_val(value):
203
 def str_val(value):
212
     try:
204
     try:
213
         return str(value)
205
         return str(value)
214
-    except Exception as e:
215
-        raise ValidationError("Not able to convert value to string : " + str(e))
206
+    except Exception as exp:
207
+        raise ValidationError("Can't to convert value to string: " + str(exp))
216
 
208
 
217
 ##@brief Validate using a regex
209
 ##@brief Validate using a regex
218
 def regex_val(value, pattern):
210
 def regex_val(value, pattern):
229
     try:
221
     try:
230
         socket.inet_aton(value)
222
         socket.inet_aton(value)
231
         return value
223
         return value
232
-    except (TypeError,OSError):
224
+    except (TypeError, OSError):
233
         pass
225
         pass
234
     try:
226
     try:
235
         socket.inet_pton(socket.AF_INET6, value)
227
         socket.inet_pton(socket.AF_INET6, value)
236
         return value
228
         return value
237
-    except (TypeError,OSError):
229
+    except (TypeError, OSError):
238
         pass
230
         pass
239
     try:
231
     try:
240
         socket.getaddrinfo(value, 80)
232
         socket.getaddrinfo(value, 80)
241
         return value
233
         return value
242
-    except (TypeError,socket.gaierror):
234
+    except (TypeError, socket.gaierror):
243
         msg = "The value '%s' is not a valid host"
235
         msg = "The value '%s' is not a valid host"
244
         raise ValidationError(msg % value)
236
         raise ValidationError(msg % value)
245
 
237
 
246
-def custom_list_validator(value, validator_name, validator_kwargs = None):
238
+def custom_list_validator(value, validator_name, validator_kwargs=None):
247
     validator_kwargs = dict() if validator_kwargs is None else validator_kwargs
239
     validator_kwargs = dict() if validator_kwargs is None else validator_kwargs
248
     validator = Validator(validator_name, **validator_kwargs)
240
     validator = Validator(validator_name, **validator_kwargs)
249
     for item in value.split():
241
     for item in value.split():
254
 #   Default validators registration
246
 #   Default validators registration
255
 #
247
 #
256
 
248
 
257
-Validator.register_validator(
258
-    'custom_list',
259
-    custom_list_validator,
249
+Validator.register_validator('custom_list', custom_list_validator, \
260
     'A list validator that takes a "validator_name" as argument')
250
     'A list validator that takes a "validator_name" as argument')
261
 
251
 
262
-Validator.register_validator(
263
-    'dummy',
264
-    lambda value:value,
265
-    'Validate anything')
266
-
267
-Validator.register_validator(
268
-    'none',
269
-    none_val,
270
-    'Validate None')
271
-
272
-Validator.register_validator(
273
-    'string',
274
-    str_val,
275
-    'Validate string values')
276
-
277
-Validator.register_validator(
278
-    'strip',
279
-    str.strip,
280
-    'String trim')
281
-
282
-Validator.register_validator(
283
-    'int',
284
-    int_val,
285
-    'Integer value validator')
286
-
287
-Validator.register_validator(
288
-    'bool',
289
-    boolean_val,
290
-    'Boolean value validator')
291
-
292
-Validator.register_validator(
293
-    'errfile',
294
-    file_err_output,
252
+Validator.register_validator('dummy', lambda value: value, 'Validate anything')
253
+
254
+Validator.register_validator('none', none_val, 'Validate None')
255
+
256
+Validator.register_validator('string', str_val, 'Validate string values')
257
+
258
+Validator.register_validator('strip', str.strip, 'String trim')
259
+
260
+Validator.register_validator('int', int_val, 'Integer value validator')
261
+
262
+Validator.register_validator('bool', boolean_val, 'Boolean value validator')
263
+
264
+Validator.register_validator('errfile', file_err_output,\
295
     'Error output file validator (return stderr if filename is "-")')
265
     'Error output file validator (return stderr if filename is "-")')
296
 
266
 
297
-Validator.register_validator(
298
-    'directory',
299
-    directory_val,
267
+Validator.register_validator('directory', directory_val, \
300
     'Directory path validator')
268
     'Directory path validator')
301
 
269
 
302
-Validator.register_validator(
303
-    'loglevel',
304
-    loglevel_val,
305
-    'Loglevel validator')
270
+Validator.register_validator('loglevel', loglevel_val, 'Loglevel validator')
306
 
271
 
307
-Validator.register_validator(
308
-    'path',
309
-    path_val,
310
-    'path validator')
272
+Validator.register_validator('path', path_val, 'path validator')
311
 
273
 
312
-Validator.register_validator(
313
-    'host',
314
-    host_val,
315
-    'host validator')
274
+Validator.register_validator('host', host_val, 'host validator')
316
 
275
 
317
-Validator.register_validator(
318
-    'regex',
319
-    regex_val,
276
+Validator.register_validator('regex', regex_val, \
320
     'RegEx name validator (take re as argument)')
277
     'RegEx name validator (take re as argument)')
321
 
278
 
322
-Validator.create_list_validator(
323
-    'list',
324
-    Validator('strip'),
325
-    description = "Simple list validator. Validate a list of values separated by ','",
326
-    separator = ',')
327
-
328
-Validator.create_list_validator(
329
-    'directory_list',
330
-    Validator('directory'),
331
-    description = "Validator for a list of directory path separated with ','",
332
-    separator = ',')
333
-
334
-Validator.create_write_list_validator(
335
-    'write_list',
336
-    Validator('directory'),
337
-    description = "Validator for an array of values which will be set in a string, separated by ','",
338
-    separator = ',')
339
-
340
-Validator.create_re_validator(
341
-    r'^https?://[^\./]+.[^\./]+/?.*$',
342
-    'http_url',
279
+Validator.create_list_validator('list', Validator('strip'), description=\
280
+    "Simple list validator. Validate a list of values separated by ','", \
281
+    separator=',')
282
+
283
+Validator.create_list_validator( \
284
+    'directory_list', \
285
+    Validator('directory'), \
286
+    description="Validator for a list of directory path separated with ','", \
287
+    separator=',')
288
+
289
+Validator.create_write_list_validator( \
290
+    'write_list', \
291
+    Validator('directory'), \
292
+    description="Validator for an array of values \
293
+        which will be set in a string, separated by ','",
294
+    separator=',')
295
+
296
+Validator.create_re_validator( \
297
+    r'^https?://[^\./]+.[^\./]+/?.*$', \
298
+    'http_url', \
343
     'Url validator')
299
     'Url validator')
300
+
344
 ##@brief Validator for Editorial model component
301
 ##@brief Validator for Editorial model component
345
 #
302
 #
346
 # Designed to validate a conf that indicate a class.field in an EM
303
 # Designed to validate a conf that indicate a class.field in an EM
347
 #@todo modified the hardcoded dyncode import (it's a warning)
304
 #@todo modified the hardcoded dyncode import (it's a warning)
348
 def emfield_val(value):
305
 def emfield_val(value):
349
-    LodelContext.expose_modules(globals(), {
350
-        'lodel.plugin.hooks': ['LodelHook']})
306
+    LodelContext.expose_modules(globals(), \
307
+        {'lodel.plugin.hooks': ['LodelHook']})
351
     spl = value.split('.')
308
     spl = value.split('.')
352
     if len(spl) != 2:
309
     if len(spl) != 2:
353
         msg = "Expected a value in the form CLASSNAME.FIELDNAME but got : %s"
310
         msg = "Expected a value in the form CLASSNAME.FIELDNAME but got : %s"
357
     @LodelHook('lodel2_dyncode_bootstraped')
314
     @LodelHook('lodel2_dyncode_bootstraped')
358
     def emfield_conf_check(hookname, caller, payload):
315
     def emfield_conf_check(hookname, caller, payload):
359
         import leapi_dyncode as dyncode # <-- dirty & quick
316
         import leapi_dyncode as dyncode # <-- dirty & quick
360
-        classnames = { cls.__name__.lower():cls for cls in dyncode.dynclasses}
317
+        classnames = { cls.__name__.lower(): cls for cls in dyncode.dynclasses}
361
         if value[0].lower() not in classnames:
318
         if value[0].lower() not in classnames:
362
             msg = "Following dynamic class do not exists in current EM : %s"
319
             msg = "Following dynamic class do not exists in current EM : %s"
363
             raise SettingsValidationError(msg % value[0])
320
             raise SettingsValidationError(msg % value[0])
370
 ##@brief Validator for plugin name & optionnaly type
327
 ##@brief Validator for plugin name & optionnaly type
371
 #
328
 #
372
 #Able to check that the value is a plugin and if it is of a specific type
329
 #Able to check that the value is a plugin and if it is of a specific type
373
-def plugin_validator(value, ptype = None):
374
-    LodelContext.expose_modules(globals(), {
330
+def plugin_validator(value, ptype=None):
331
+    LodelContext.expose_modules(globals(), { \
375
         'lodel.plugin.hooks': ['LodelHook']})
332
         'lodel.plugin.hooks': ['LodelHook']})
376
     value = copy.copy(value)
333
     value = copy.copy(value)
377
     @LodelHook('lodel2_dyncode_bootstraped')
334
     @LodelHook('lodel2_dyncode_bootstraped')
378
     def plugin_type_checker(hookname, caller, payload):
335
     def plugin_type_checker(hookname, caller, payload):
379
-        LodelContext.expose_modules(globals(), {
380
-            'lodel.plugin.plugins': ['Plugin'],
336
+        LodelContext.expose_modules(globals(), { \
337
+            'lodel.plugin.plugins': ['Plugin'], \
381
             'lodel.plugin.exceptions': ['PluginError']})
338
             'lodel.plugin.exceptions': ['PluginError']})
382
         if value is None:
339
         if value is None:
383
             return
340
             return
395
     return value
352
     return value
396
 
353
 
397
 
354
 
398
-Validator.register_validator(
399
-    'plugin',
400
-    plugin_validator,
355
+Validator.register_validator( \
356
+    'plugin', \
357
+    plugin_validator, \
401
     'plugin name & type validator')
358
     'plugin name & type validator')
402
 
359
 
403
-Validator.register_validator(
404
-    'emfield',
405
-    emfield_val,
360
+Validator.register_validator( \
361
+    'emfield', \
362
+    emfield_val, \
406
     'EmField name validator')
363
     'EmField name validator')
407
 
364
 
408
 #
365
 #
427
 ##@brief Global specifications for lodel2 settings
384
 ##@brief Global specifications for lodel2 settings
428
 LODEL2_CONF_SPECS = {
385
 LODEL2_CONF_SPECS = {
429
     'lodel2': {
386
     'lodel2': {
430
-        'debug': (  True,
431
-                    Validator('bool')),
432
-        'sitename': (   'noname',
433
-                        Validator('strip')),
434
-        'runtest': (    False,
435
-                        Validator('bool')),
387
+        'debug': (True, Validator('bool')),
388
+        'sitename': ('noname', Validator('strip')),
389
+        'runtest': (False, Validator('bool')),
436
     },
390
     },
437
     'lodel2.logging.*' : {
391
     'lodel2.logging.*' : {
438
-        'level': (  'ERROR',
439
-                    Validator('loglevel')),
440
-        'context': (    False,
441
-                        Validator('bool')),
442
-        'filename': (   "-",
443
-                        Validator('errfile', none_is_valid = False)),
444
-        'backupcount': (    5,
445
-                            Validator('int', none_is_valid = False)),
446
-        'maxbytes': (   1024*10,
447
-                        Validator('int', none_is_valid = False)),
392
+        'level': ('ERROR', Validator('loglevel')),
393
+        'context': (False, Validator('bool')),
394
+        'filename': ("-", Validator('errfile', none_is_valid=False)),
395
+        'backupcount': (5, Validator('int', none_is_valid=False)),
396
+        'maxbytes': (1024*10, Validator('int', none_is_valid=False)),
448
     },
397
     },
449
     'lodel2.editorialmodel': {
398
     'lodel2.editorialmodel': {
450
-        'emfile': ( 'em.pickle', Validator('strip')),
451
-        'emtranslator': ( 'picklefile', Validator('strip')),
452
-        'dyncode': ( 'leapi_dyncode.py', Validator('strip')),
453
-        'groups': ( '', Validator('list')),
454
-        'editormode': ( False, Validator('bool')),
399
+        'emfile': ('em.pickle', Validator('strip')),
400
+        'emtranslator': ('picklefile', Validator('strip')),
401
+        'dyncode': ('leapi_dyncode.py', Validator('strip')),
402
+        'groups': ('', Validator('list')),
403
+        'editormode': (False, Validator('bool')),
455
     },
404
     },
456
     'lodel2.datasources.*': {
405
     'lodel2.datasources.*': {
457
         'read_only': (False, Validator('bool')),
406
         'read_only': (False, Validator('bool')),
458
-        'identifier': ( None, Validator('string')),
407
+        'identifier': (None, Validator('string')),
459
     },
408
     },
460
     'lodel2.auth': {
409
     'lodel2.auth': {
461
         'login_classfield': ('user.login', Validator('emfield')),
410
         'login_classfield': ('user.login', Validator('emfield')),
462
         'pass_classfield': ('user.password', Validator('emfield')),
411
         'pass_classfield': ('user.password', Validator('emfield')),
463
     },
412
     },
464
-}
413
+}

Loading…
Cancel
Save