Drkcore

28 02 2013 Python Tweet

FlaskのViewのメタプログラミングの例がわかりやすかった。

MethodViewのコードを読んでたら、例としてわかりやすかったのでメモ。どういう動きをするのかはあらかじめ「Pythonのメタプログラミング (メタクラス) を理解したい人のための短いコード片と禅問答」を読んでおくと良いと思う。

class MethodViewType(type):
    def __new__(cls, name, bases, d):
        rv = type.__new__(cls, name, bases, d)
        if 'methods' not in d:
            methods = set(rv.methods or [])
            for key in d:
                if key in http_method_funcs:
                    methods.add(key.upper())
            if methods:
                rv.methods = sorted(methods)
        return rv

class MethodView(View):
    __metaclass__ = MethodViewType

    def dispatch_request(self, *args, **kwargs):
        meth = getattr(self, request.method.lower(), None)
        if meth is None and request.method == 'HEAD':
            meth = getattr(self, 'get', None)
        assert meth is not None, 'Unimplemented method %r' % request.method
        return meth(*args, **kwargs)

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021