LoginSignup
69
64

More than 5 years have passed since last update.

Flaskのrequest.argsでパラメータの処理について

Last updated at Posted at 2013-03-01

知ってたら楽できるのでFlask使う人には覚えて欲しい

flask.request.argsの実態はソース読むと以下のインスタンスですね。

werkzeug.datastructures.ImmutableMultiDict

request.argsで一番使うメソッドは多分getだと思うんですが実態は

from werkzeug.datastructures import TypeConversionDict

のgetメソッドです。

これのヘルプ読むと型指定できるんですね。

 |  ----------------------------------------------------------------------
 |  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.
 |  
 |  ----------------------------------------------------------------------

つまり、このパラメータはINT型などの指定が簡単に出来るんですね。

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

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

Flaskのドキュメント読むだけでは気付けないことが結構あるのでwerkzeugのドキュメントや実装読んだりしてみると意外と発見があるのでぜひ読んで下さい。

これをもっと拡張すると自作のデータ型を使ってパラメータを受け取ることも可能です。

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
        else:
           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パラメータを受け取ってます。

69
64
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
69
64