Parametizer

Byron Ruth edited this page May 2, 2013 · 1 revision

restlib2 comes with convenient Parametizer class for cleaning GET parameters.

The supported GET parameters can be listed with their default values in the body of class. In it's simplest form, you have this.

from restlib2.params import Parametizer

class MyParametizer(Parametizer):
    sort = 'order'
    direction = 'asc'
    page = 1
    per_page = 10

The trouble, however, is parsing the values for each parameter. Everything is string since GET parameters are part of the URL. Parametizer supports clean_* methods for each parameter. For example, both page and per_page are integers, but the request.GET.get('page') would simply return it as a string if defined. We can define a clean method for each of the parameters.

from restlib2.params import Parametizer

class MyParametizer(Parametizer):
    sort = 'order'
    direction = 'asc'
    page = 1
    per_page = 10

    def clean_page(self, value):
        return int(value)

    def clean_per_page(self, value):
        return int(value)

A clean method takes the value and returns the coerced value. If an exception is raised within a clean method (which could easily happen if page is and empty string or None), it fallbacks to the default value. So /some/path/?page= would raise a ValueError when cleaning page, so it correctly falls back to page 1.

To use the class, simply initialize it and use the clean method with a set of parameters:

p = MyParametizer()
# Returns a dict
params = p.clean(request.GET)

Cleaners

For convenience a set of cleaners are are available at restlib2.params.param_cleaners

clean_bool

Converts a string to a boolean based using a few options:

  • ['t', 'true', '1', 'yes']True
  • ['f', 'false', '0', 'no']False
>>> param_cleaners.clean_bool('1')
True
>>> param_cleaners.clean_bool('TRUE') # case doesn't matter
True

clean_int

Coerces a string to an integer.

>>> param_cleaners.clean_int('1')
1

clean_float

Coerces a string to a float.

>>> param_cleaners.clean_float('1.3')
1.3

clean_string

Strips whitespace around the string.

>>> param_cleaners.clean_string(' foo   ')
'foo'
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.