Parse Input with Schemas

In the common “web form” use case you already get parameters mapped to keys. That’s usually the job of your web framework. However sometimes it’s not that easy: Before you can do input validation, you need to parse the user input from a string and convert that into a dict.

This is where ‘’PositionalArgumentsParsingSchema()’’ might help you: This schema takes a string and extracts several parameters from it. So you can use it to transform "foo, 42" into dict(name="foo", value=42).

class pycerberus.schemas.PositionalArgumentsParsingSchema(self)

This schema parses a string containing arguments within a specified order and returns a dict where each of these parameters is mapped to a specific key for easy retrieval.

You specify the order of parameters (and the keys) in the class-level attribute parameter_order:

class ConfigListSchema(PositionalArgumentsParsingSchema):
    first_key = StringValidator()
    second_key = IntegerValidator()
    parameter_order = (first_key, second_key)

By default the items are separated by comma though you can override in the method separator_pattern(). If there are more items than keys specified, this schema will behave like any other schema (depending if you set the class-level attribute allow_additional_parameters).

aggregate_values(parameter_names, arguments, context)

This method can manipulate or aggregate parsed arguments. In this class, it’s just a noop but sub classes can override this method to do more interesting stuff.

keys()

Return all keys defined by this specific validator class.

message_for_key(key, context)

Return a message for a specific key. Implement this method if you want to avoid calls to messages() which might be costly (otherwise implementing this method is optional).

messages()

Return all messages which are defined by this validator as a key/message dictionary. Alternatively you can create a class-level dictionary which contains these keys/messages.

You must declare all your messages here so that all keys are known after this method was called.

Calling this method might be costly when you have a lot of messages and returning them is expensive. You can reduce the overhead in some situations by implementing message_for_key()

process(value, context=None)

This is the method to validate your input. The validator returns a (Python) representation of the given input value.

In case of errors a InvalidDataError is thrown.

This schema is used for example in pymta. to parse the SMTP command strings. Also I used it in my OhlohWidgetsMacro: Trac macros can get parameters but these are passed as a single string so the schema takes care of separating these arguments.