Request Parsers

When working with Forms or Messages you will likely want to take an HTTP request and parse its data into a Form or Message instance. This is where request parsers come in. The parsers are used by controllers to transform requests into containers (forms, messages, or other custom classes).

Parsing

Use Controller.parse_request() to parser the request and return a parser object.

Controller.parse_request(container=None, fallback=None, parser=None)[source]

Parses request data (like GET, POST, JSON, XML) into a container (like a Form or Message) instance using a RequestParser. By default, it assumes you want to process GET/POST data into a Form instance, for that simple case you can use:

data = self.parse_request()

provided you’ve set the Form attribute of the Meta class.

For example:

from ferris import Controller, route
import wtforms

class MyForm(wtforms.Form):
    name = wtforms.fields.StringField("Name")

class Example(Controller):
    class Meta:
        Form = MyForm

    @route
    def form(self):
        if self.request.method != "GET":
            parser = self.parse_request()
            return parser.container.name

You can pass in a different Form to parse_request if needed:

self.parse_request(container=MyOtherForm)

If you already have some data in an object you can use it as default values, for example:

instance = MyModel(name="Brian")
parser = self.parse_request(fallback=instance)

Additionally if you want to use a parser other than the default Form parser:

parser = self.parse_request(container=MyMessage, parser='Message')

The Parser Instance

The parse_request method returns a parser instance.

class ferris.core.request_parsers.RequestParser[source]

Contains all of the information about a parsed request including the container (a Form or Message instance) with the results.

RequestParser.validate()[source]

Calls the relevant validate method on the container. Returns True if the container is valid.

RequestParser.update(obj)[source]

Populates the given object with data from the container.

RequestParser.container

The container that’s populated with the data from the request

RequestParser.data

The data contained in the container.

RequestParsers.errors

Validation errors (if any).

The most common usage is to use the parser to update a Model instance:

parser = self.parse_request(fallback=my_model_instance)
if parser.validate():
    parser.update(my_model_instance)
    my_model_instance.put()