python - 使用 flask 方法 View

标签 python flask

我正在尝试调整它:

http://flask.pocoo.org/docs/views/

进入蓝图本身(基于我看过的其他蓝图)。将 api 注册从应用程序抽象到蓝图初始化中。这是来自 flask 文档的代码,有一些更改。

这似乎可行:

 class MyAPI(MethodView):

    def __init__(self, name):
        self.name = name
        bp = Blueprint(name, __name__)
        bp_endpoint = '{0}_api'.format(name)
        bp_url = '/{0}/'.format(name)
        bp_pk = '{0}_tag'.format(name)
        self.register_api(bp, bp_endpoint, bp_url, bp_pk, 'string')
        self._blueprint = bp

    def register_api(self, blueprint, endpoint, url, pk='id', pk_type='int'):
        view_func = self.as_view(endpoint)
        blueprint.add_url_rule(url, defaults={pk: None},
                         view_func=view_func, methods=['GET',])
        blueprint.add_url_rule(url, view_func=view_func, methods=['POST',])
        blueprint.add_url_rule('{0}<{1}:{2}>'.format(url, pk_type, pk), view_func=view_func,
                         methods=['GET', 'PUT', 'DELETE'])

    def get(self, my_tag):
         #... with post, put methods etc.

然后在我的应用程序中我可以这样做:

m = MyAPI('my')
app.register_blueprint(m._blueprint)

这似乎有效,注册 url 这样我就可以得到:

Map([<Rule '/my/' (POST, OPTIONS) -> my.my_api>,
 <Rule '/my/<my_tag>' (PUT, HEAD, DELETE, OPTIONS, GET) -> my.my_api>,
 <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
 <Rule '/my/' (HEAD, OPTIONS, GET) -> my.my_api>])

但是,现在转到路线时出现错误(我刚刚尝试了 GET):

Traceback (most recent call last):
  File "/media/686e26f8-c6d4-4448-8fe4-c19802726dcb/projects/1_current/private/pycleaver/venv/lib/python2.7/site-packages/flask/app.py", line 1518, in __call__
    return self.wsgi_app(environ, start_response)
  File "/media/686e26f8-c6d4-4448-8fe4-c19802726dcb/projects/1_current/private/pycleaver/venv/lib/python2.7/site-packages/flask/app.py", line 1506, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/media/686e26f8-c6d4-4448-8fe4-c19802726dcb/projects/1_current/private/pycleaver/venv/lib/python2.7/site-packages/flask/app.py", line 1504, in wsgi_app
    response = self.full_dispatch_request()
  File "/media/686e26f8-c6d4-4448-8fe4-c19802726dcb/projects/1_current/private/pycleaver/venv/lib/python2.7/site-packages/flask/app.py", line 1264, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/media/686e26f8-c6d4-4448-8fe4-c19802726dcb/projects/1_current/private/pycleaver/venv/lib/python2.7/site-packages/flask/app.py", line 1262, in full_dispatch_request
    rv = self.dispatch_request()
  File "/media/686e26f8-c6d4-4448-8fe4-c19802726dcb/projects/1_current/private/pycleaver/venv/lib/python2.7/site-packages/flask/app.py", line 1248, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/media/686e26f8-c6d4-4448-8fe4-c19802726dcb/projects/1_current/private/pycleaver/venv/lib/python2.7/site-packages/flask/views.py", line 83, in view
    self = view.view_class(*class_args, **class_kwargs)
**TypeError: __init__() takes exactly 2 arguments (1 given)**

aa 这​​比我认为的 atm 低一两个级别。任何输入感谢我错过的东西。我认为这可能与 register_api 中的 view_func 最初有关。

编辑:

一个答案

class MyAPI(MethodView):  

    def __init__(self, name):
        self.name = name
        bp = Blueprint(name, __name__)
        self.endpoint = '{0}_api'.format(name)
        self.url = '/{0}/'.format(name)
        self.pk = '{0}_tag'.format(name)
        self._blueprint = bp
        self.register_api(self._blueprint, self.endpoint, self.url, self.pk)

    def register_api(self, bp, endpoint, url, pk ='id', pk_type='int'):
        view_func = self.__class__.as_view(endpoint)
        bp.add_url_rule(url, defaults={pk: None},
                     view_func=view_func, methods=['GET',])
        bp.add_url_rule(url, view_func=view_func, methods=['POST',])
        bp.add_url_rule('{0}<{1}:{2}>'.format(url, pk_type, pk), view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])

最佳答案

我认为你可以让你的初始化方法只有一个参数:

def __init__(self):
    bp = Blueprint("what?", __name__)  # here
    bp_endpoint = '{0}_api'.format(name)
    bp_url = '/{0}/'.format(name)
    bp_pk = '{0}_tag'.format(name)
    self.register_api(bp, bp_endpoint, bp_url, bp_pk, 'string')
    self._blueprint = bp

或者在 as_view 中提供足够的值而不修改您的初始化方法。

def register_api(self, blueprint, endpoint, url, pk='id', pk_type='int'):
    view_func = self.as_view(endpoint, name="what?")  # here
    # ... omit ...

但在我看来,在方法 View 中创建蓝图并不是一个好主意。蓝图是一个子应用程序,应该由多个 View 共享。

关于python - 使用 flask 方法 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10656387/

相关文章:

postgresql - 如何将 pytest fixtures 与 Flask-SQLAlchemy 和 PostgreSQL 结合起来?

python - WTForms-用字符串值预填充文本区域字段?

python - 在 Flask 模板中显示属性对象而不是值

python - 如何在 uWSGI 中正确加载 Flask 应用程序模块?

python - 如何使用 python 有效地找到两个大文件的交集?

python - SWIG C++/Python 绑定(bind)和支持带有 std::enable_if 的条件成员

python - 如何在没有 Pandas 的情况下读取、格式化、排序和保存 csv 文件

python - 更新 ttk.Notebook 中选项卡开关的框架

python - Flask:获取当前蓝图webroot

python - Katalon Export - 机器人框架问题