You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Flask实现多文本文件上传时AssertionError报错的解决咨询

解决Flask中「View function mapping is overwriting an existing endpoint function」错误

嘿,这个问题我之前也踩过坑!你看,你的代码里有两个视图函数都叫upload_file——一个是负责返回上传页面的/upload路由,另一个是处理文件上传逻辑的/uploader路由。

Flask默认会把函数名作为每个路由的唯一标识(也就是endpoint),当两个函数同名时,后定义的那个会直接覆盖掉前面的,这就触发了这个AssertionError。

解决方法超简单,只需要重命名其中一个函数就行:

把处理文件上传的那个函数改个名字,比如叫handle_upload,修改后的flask.py代码如下:

from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)

@app.route('/upload')
def upload_file():
    return render_template('upload.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def handle_upload():  # 这里修改了函数名,和上面的upload_file区分开
    if request.method == 'POST':
        f = request.files['file']
        f.save(secure_filename(f.filename))
        return 'file uploaded successfully'

if __name__ == '__main__':
    app.run(debug = True)

这样两个函数的名字不一样了,Flask就能正确识别两个不同的endpoint,不会再出现覆盖的问题啦。

另外提个小知识点:如果你不想改函数名,也可以在路由装饰器里手动指定endpoint,比如:

@app.route('/uploader', methods=['GET', 'POST'], endpoint='upload_handler')
def upload_file():
    # 上传逻辑...

不过这种方式不如直接重命名函数直观,一般还是推荐用不同的函数名来区分不同的视图逻辑。

内容的提问来源于stack exchange,提问作者elly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:28:24