Permalink
Browse files

Fail during ValidatingItem construction if required Field is missing.

ValidatingItem now raises ValueError if it has an Field with a
required=True attribute and it is not set during construction.

Also fix a bug with validation.
  • Loading branch information...
doublea committed Feb 26, 2012
1 parent cfc822f commit 05830cfa3aa55850c94370de3377b15b795cb4f7
Showing with 9 additions and 7 deletions.
  1. +9 −7 scraping/scraping/items.py
View
@@ -6,19 +6,21 @@
from scrapy.item import Item, Field
class ValidatingItem(Item):
- """ Item subclass that calls field['validator'] when setting a field's value
-
-
- """
+ def __init__(self, *args, **kwargs):
+ super(ValidatingItem, self).__init__(*args, **kwargs)
+ for name, field in self.fields.iteritems():
+ if 'required' in field and field['required'] and name not in self._values:
+ raise ValueError("Field %s is required" % name)
+
def __setitem__(self, key, value):
- if key in self.fields and 'validator' in self[key]:
- new_value = self[key]['validator'](value)
+ if key in self.fields and 'validator' in self.fields[key]:
+ new_value = self.fields[key]['validator'](value)
if new_value is not None:
value = new_value
super(ValidatingItem, self).__setitem__(key, value)
class SubstitutesItem(ValidatingItem):
- id = Field(validator=int)
+ id = Field(validator=int, required=True)
date = Field()
name = Field()
chamber = Field()

0 comments on commit 05830cf

Please sign in to comment.