【问题标题】:Flask - reason for view function mapping is overwriting errorFlask - 视图函数映射的原因是覆盖错误
【发布时间】:2018-05-13 12:27:06
【问题描述】:

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

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】:

这是问题:

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

您的视图名称应该是唯一的。您不能有两个具有相同名称的烧瓶视图方法。将 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 中,您没有传递名称,因此烧瓶采用方法名称从中创建规则。由于此地图是字典,因此它必须是唯一的。

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

【讨论】:

  • 我不明白你,你在哪里看到相同的名字?
  • def start(adv_id):def add(): 不应为另一个视图名称再次重复。
  • 你的意思是同名函数start()吗?
  • 是函数名也开始和添加。
  • 这是我想到 Flask 的缺点,因为我在 @app.route 之后声明了函数
猜你喜欢
  • 1970-01-01
  • 2021-08-08
  • 2013-11-26
  • 2015-05-03
  • 2019-11-14
  • 2013-06-19
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多