Help us understand the problem. What is going on with this article?


More than 5 years have passed since last update.





from werkzeug.datastructures import TypeConversionDict



 |  ----------------------------------------------------------------------
 |  Methods inherited from TypeConversionDict:
 |  get(self, key, default=None, type=None)
 |      Return the default value if the requested data doesn't exist.
 |      If `type` is provided and is a callable it should convert the value,
 |      return it or raise a :exc:`ValueError` if that is not possible.  In
 |      this case the function will return the default as if the value was not
 |      found:
 |      >>> d = TypeConversionDict(foo='42', bar='blub')
 |      >>> d.get('foo', type=int)
 |      42
 |      >>> d.get('bar', -1, type=int)
 |      -1
 |      :param key: The key to be looked up.
 |      :param default: The default value to be returned if the key can't
 |                      be looked up.  If not further specified `None` is
 |                      returned.
 |      :param type: A callable that is used to cast the value in the
 |                   :class:`MultiDict`.  If a :exc:`ValueError` is raised
 |                   by this callable the default value is returned.
 |  ----------------------------------------------------------------------


簡単な例を挙げると、参照系のAPIでoffset, limitパラメータをよく作ると思いますが型の指定を含めて下の2行で出来てしまいます。

    offset = request.args.get("offset", default=0, type=int)
    limit = request.args.get("limit", default=10, type=int)



class SortType(object):
    accepts = ["-time", "-size", "+time", "+size"]    
    default = ["-time"]

    def __init__(self, sort_parameter):
        super(SortType, self).__init__()    
        if sort_parameter in self.accepts:
           self.sort = sort_parameter
           self.sort = self.default

    def __repr__(self):
        return self.sort

    def __str__(self):
        return self.sort
sort = '%s' % request.args.get("sort", type=SortType)

いくつかのソートタイプとデフォルトのソートをもつクラスを定義して type にそれを定義して sortパラメータを受け取ってます。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away