Flask-视图函数映射的原因是覆盖错误

问题描述 投票:0回答:1

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

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()

您可以看到,我有两种方法add()用于GET和POST请求。

此消息是什么意思?

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

@app.route('/update/<int:adv_id>', methods=['PUT'])
def start(adv_id):
    return 'update'
python python-3.x flask
1个回答
2
投票
这是问题:

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

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

[编辑]

正如@Oleg询问/评论的那样,此唯一名称是一个缺点。如果您阅读了Flask的源代码,则原因很明显。从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使用方法名称从中创建规则。由于此地图是字典,因此它必须是唯一的。

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

© www.soinside.com 2019 - 2024. All rights reserved.