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

Contents of /trunk/core/fieldparse.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 163 - (show annotations) (download) (as text)
Sat Oct 22 07:05:14 2005 UTC (12 years, 9 months ago) by hadfield
File MIME type: text/x-python
File size: 6007 byte(s)
fixed a minor bug with regards to length verification.
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 = keywords.get("default", None)
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 if field.min_size and len(field.value) < field.min_size:
116 err_msg = ("%s is too small! Minimum is %s characters" %
117 (field.name, field.min_size))
118
119 if field.regex is not None and field.value != field.default:
120 regex = re.compile(field.regex, re.UNICODE)
121 if not regex.match(field.value):
122 err_msg = ("%s contained illegal characters." %
123 (field.name))
124
125 if err_msg != "":
126 field.set_value("")
127 raise FieldParseError(err_msg)
128
129 if field.filter is not None:
130 field.set_value(field.filter(field.value))
131
132 return True
133
134 def _get_values(self):
135 """Returns a dictionary of all fields and their respective values.
136
137 @return: {field.dest: field.value} dictionary
138 """
139 retval = {}
140 for field in self.fields:
141 retval[field.dest] = field.value
142 return retval
143
144 def add_field(self, field_name, **keywords):
145 """Adds a Field to our field list.
146
147 @param field_name: The name of the form field.
148 @keywords: A list of valid Field options.
149 """
150 self.fields.append(Field(field_name, **keywords))
151
152 def parse_form(self):
153 """Sets form values for all of our fields and validates them.
154
155 @return: dictionary containing all fields and their respective values.
156 """
157
158 # Get the field values from the form.
159 err = ""
160 for field in self.fields:
161 try:
162 # err == "" is used to enable/disable the check. If an error
163 # has already been raised then don't check any more, just set.
164 # This way all of our field data will still be populated
165 # instead of choking on the first type mismatch.
166 form_value = self.request.getvalue(field.name, field.default)
167 field.set_value(form_value, err == "")
168
169 except FieldParseError, err_msg:
170 err = err_msg
171
172 if err != "":
173 self.error_method(err, self._get_values())
174 return False
175
176 try:
177 self._check_fields()
178
179 except FieldParseError, err_msg:
180 self.error_method(err_msg, self._get_values())
181 return False
182
183 return self._get_values()
184
185 def set_requester(self, request):
186 """Set the requester object.
187
188 @param request: A request object that contains a getvalue function.
189 For example, a cgi.FieldStorage object.
190 """
191 self.request = request

Properties

Name Value
svn:keywords Id

  ViewVC Help
Powered by ViewVC 1.1.20