2

I have a set of Colander SchemaNodes used with Pyramid/Cornice in an API. For some querystring args, a range is passed (ie time=X-Y means a time range from X to Y where X and Y are integers representing epochs). I currently validate this with a RegEx() validator to ensure an epoch or epoch range is passed in:

class TimeOrRange(SchemaNode):
    schema_type = String
    location = "querystring"
    description = 'Time (or range) in epochs: ssssssssss(-ssssssssss)'
    validator = Regex("^[0-9]{10}\-{0,1}[0-9]{0,10}$")

I then use this in a MappingSchema which is then tied to my Cornice view with @view(schema=TimedThingGet):

class TimedThingGet(MappingSchema):
    time = TimeOrRange(missing=drop)

What I would like to do is update the return value in my TimeOrRange SchemaNode code so time in TimedThingGet is a tuple of time ranges. In other words, if time=X-Y is passed in to a TimedThingGet instance, then time=(x, y) is returned in the validated data. Similarly, if only X is passed in, then I want Y to be set to the epoch of now().

It looks like set_value() is the way to go, and here's where the problem get's some extra credit:

  1. Does set_value get called before or after validation?
  2. Does set_value have access to the validator such that a RegEx validator which creates regex groups could then be used to set my tuple: time=(validated.match.group[1], validated.match.group[2])?
Tim Tisdall
  • 9,914
  • 3
  • 52
  • 82
hamx0r
  • 4,081
  • 1
  • 33
  • 46

1 Answers1

1

I think you should actually look at:

Preparer callable that you can pass to SchemaNode:

http://docs.pylonsproject.org/projects/colander/en/latest/interfaces.html?highlight=preparer#colander.interfaces.Preparer

It will allow you to manipulate the data before it is passed to validators

And optionally at:

http://docs.pylonsproject.org/projects/colander/en/latest/binding.html#what-is-schema-binding

Which allows you set additional properies after schema is instantiated.

Ergo
  • 1,205
  • 9
  • 16
  • Great advice. A missing piece of using a preparer is that one must use the Function() validator with a custom validator function to parse the prepared value. I say this only because my original question wanted to make use of groups from a RegEx validator, which is not directly possible. The workaround is to use a regex in a preparer and save groups to, say, a list. A custom validator function can then take the list and validate. – hamx0r Jul 17 '15 at 15:00