Flask-视图函数映射的原因是覆盖错误 [英] Flask - reason for view function mapping is overwriting error

查看:53
本文介绍了Flask-视图函数映射的原因是覆盖错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在尝试使用渲染时出现此错误:

Why I get this error when tried to use rendering:

Traceback (most recent call last):
  File "d:\Projects\jara.md\backend\flask\__init__.py", line 31, in <module>
    @app.route('/update/<int:adv_id>', methods=['PUT'])
  File "c:\Python27\lib\site-packages\flask\app.py", line 1080, in decorator
    self.add_url_rule(rule, endpoint, f, **options)
  File "c:\Python27\lib\site-packages\flask\app.py", line 64, in wrapper_func
    return f(self, *args, **kwargs)
  File "c:\Python27\lib\site-packages\flask\app.py", line 1051, in add_url_rule
    'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: start

代码列表为:

app = Flask(__name__)


@app.route('/add', methods=['POST'])
def add():
    return 'Add'


@app.route('/start/<int:adv_id>', methods=['PUT'])
def start(adv_id):
    return 'start'

### Rendering ###

@app.route('/add', methods=['GET'])
def add():
    return render_template('add.html')

if __name__ == "__main__":
    app.run()

如您所见,我有两种方法GET和POST请求 add().

As you can see I have two methods add() for GET and POST requests.

此消息是什么意思?

 self.add_url_rule(rule, endpoint, f, **options)


@app.route('/update/<int:adv_id>', methods=['PUT'])
def start(adv_id):
    return 'update'

推荐答案

这是问题所在

@app.route('/update/<int:adv_id>', methods=['PUT'])
def start(adv_id):
    return 'update'

您查看的名称应该唯一.您不能有两个名称相同的flask视图方法.将 start add 方法命名为其他唯一的方法.

You view names should be unique. You can't have two flask view methods with the same name. Name start and add methods to something else which is unique.

正如@Oleg询问/评论的那样,此唯一名称是一个缺点.如果您阅读了Flask的源代码,则原因很明显.从源代码

As @Oleg asked/commented that this unique name is a disadvantage. The reason for this is clear if you read the source code of Flask. From the source code

"""
Basically this example::
    @app.route('/')
    def index():
        pass Is equivalent to the following::

    def index():
        pass

    app.add_url_rule('/', 'index', index)

If the view_func is not provided you will need to connect the endpoint to a view function like so::

    app.view_functions['index'] = index
"""

因此flask将URL规则与视图函数的名称映射.在@ app.route中,您没有传递名称,所以flask使用方法名称从中创建规则.由于此地图是字典,因此必须是唯一的.

So flask maps URL rule with the name of view function. in @app.route you are not passing a name so flask takes the method name creates the rule from it. Since this map is a dictionary it needs to be unique.

因此,您可以使用具有相同名称的视图函数(只要您为视图传递了不同的名称,就不要使用该函数)

So, you can have view function with the same names(which you shouldn't as long as you pass the different name for the view)

这篇关于Flask-视图函数映射的原因是覆盖错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆