/[glsr]/trunk/core/fieldparse.py
Gentoo

Contents of /trunk/core/fieldparse.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 119 - (show annotations) (download) (as text)
Sat Aug 6 07:30:47 2005 UTC (9 years, 4 months ago) by hadfield
File MIME type: text/x-python
File size: 6120 byte(s)
enabled field type checking. renamed filter -> ffilter, type -> ftype. updated create to use ffilter.
1 # Copyright 2005 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3 #
4
5 """A basic form field parser."""
6
7 __revision__ = '$Id$'
8 __authors__ = ['Scott Hadfield <hadfield@gentoo.org>']
9 __modulename__ = 'fieldparse'
10
11
12 class FieldParseError(Exception): pass
13
14 def show_error(msg, fields):
15 pass
16
17 class Field:
18 """Defines and sets the attributes for a form field."""
19
20 def __init__(self, name, **keywords):
21 """Create a Field object.
22
23 @param name: The name of the form field.
24 @keywords: A list of valid Field options.
25 """
26
27 self.name = name
28 self.dest = keywords.get("dest", name)
29 self.default = str(keywords.get("default", ""))
30 self.required = keywords.get("required", False)
31 self.filter = keywords.get("ffilter", None)
32 self.regex = keywords.get("regex", None)
33 self.min_size = keywords.get("min_size", 0)
34 self.max_size = keywords.get("max_size", -1)
35 self.type = keywords.get("ftype", None)
36 self.value = self.default
37
38 self.TYPE_CHECKER = {
39 "int": self._check_builtin,
40 "float": self._check_builtin,
41 }
42
43 def __str__(self):
44 return str(self.__dict__)
45
46 def _check_builtin(self, value):
47
48 try:
49 eval(self.type)(value)
50 except ValueError:
51 return False
52
53 return True
54
55 def set_value(self, value, check = True):
56 """Set the value of the field."""
57
58 if not check or value == "" or self.check_value(value):
59 self.value = value
60 return True
61
62 self.value = ""
63 raise FieldParseError("Value type mismatch for '%s'" % self.name)
64
65 def check_value(self, value):
66
67 checker = self.TYPE_CHECKER.get(self.type)
68 if checker is None:
69 # If no checker is set, then the test returns successfull
70 return True
71 else:
72 return checker(value)
73
74 class FieldParser:
75 """Manage and parse fields on a form."""
76
77 def __init__(self, request = None, error_method = None):
78 """Create a FieldParser object.
79
80 @param request: A request object that contains a getvalue function.
81 For example, a cgi.FieldStorage object.
82 @param error_method: The function called when a field fails it's checks
83 """
84
85 self.request = request
86
87 self.error_method = error_method
88 if self.error_method is None:
89 self.error_method = show_error()
90
91 self.fields = []
92
93 def _check_fields(self):
94 """Validate all fields.
95
96 @return: True if all fields validate.
97 """
98
99 import re
100 from cgi import escape
101
102 for field in self.fields:
103 if field.required and field.value is None:
104 field.set_value("")
105 raise FieldParseError("Missing required field '%s'" % field)
106
107 if field.value is None:
108 continue
109
110 err_msg = ""
111 if field.max_size > -1 and len(field.value) > field.max_size:
112 err_msg = ("%s is too big! Maximum is %s characters." %
113 (field.name, field.max_size))
114
115 print "here!!!!!!!!!!!!!!!!!!!!!!!!!"
116 print field.value, field.name, type(field.value)
117 if len(field.value) < field.min_size:
118 err_msg = ("%s is too small! Minimum is %s characters" %
119 (field.name, field.min_size))
120 print "here2!!!!!!!!!!!!!!!!!!!!!!!!!"
121
122 if field.regex is not None:
123 regex = re.compile(field.regex, re.UNICODE)
124 if not regex.match(field.value):
125 err_msg = ("%s contained illegal characters." %
126 (field.name))
127
128 if err_msg != "":
129 field.set_value("")
130 raise FieldParseError(err_msg)
131
132 if field.filter is not None:
133 field.set_value(field.filter(field.value))
134
135 return True
136
137 def _get_values(self):
138 """Returns a dictionary of all fields and their respective values.
139
140 @return: {field.dest: field.value} dictionary
141 """
142 retval = {}
143 for field in self.fields:
144 retval[field.dest] = field.value
145 return retval
146
147 def add_field(self, field_name, **keywords):
148 """Adds a Field to our field list.
149
150 @param field_name: The name of the form field.
151 @keywords: A list of valid Field options.
152 """
153 self.fields.append(Field(field_name, **keywords))
154
155 def parse_form(self):
156 """Sets form values for all of our fields and validates them.
157
158 @return: dictionary containing all fields and their respective values.
159 """
160
161 # Get the field values from the form.
162 err = ""
163 for field in self.fields:
164 try:
165 # err == "" is used to enable/disable the check. If an error
166 # has already been raised then don't check any more, just set.
167 # This way all of our field data will still be populated
168 # instead of choking on the first type mismatch.
169 form_value = self.request.getvalue(field.name, field.default)
170 field.set_value(form_value, err == "")
171
172 except FieldParseError, err_msg:
173 err = err_msg
174
175 if err != "":
176 self.error_method(err, self._get_values())
177 return False
178
179 try:
180 self._check_fields()
181
182 except FieldParseError, err_msg:
183 self.error_method(err_msg, self._get_values())
184 return False
185
186 return self._get_values()
187
188 def set_requester(self, request):
189 """Set the requester object.
190
191 @param request: A request object that contains a getvalue function.
192 For example, a cgi.FieldStorage object.
193 """
194 self.request = request

Properties

Name Value
svn:keywords Id

  ViewVC Help
Powered by ViewVC 1.1.20