如何捕获flask中文件大小过大的错误?

2024-09-29 21:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在flask中,有一个选项用于设置上传为app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000的文件的最大大小,但当文件超过限制时,它会进入显示RequestEntityTooLarge的网页

有没有可能,我可以除了这个错误,并显示我自己的错误页面给用户或闪光消息代替?我试图except RequestEntityTooLarge:,但它显示未知错误

关于这个例外的更多信息是here


Tags: 文件用户configapp消息网页flask选项
1条回答
网友
1楼 · 发布于 2024-09-29 21:33:36

烧瓶1.x文档:Custom Error Pages

您可以使用@app.errorhandler(413)分配函数,该函数将在文件太大时执行,并且该函数可能会显示custon模板


最低工作代码:

from flask import Flask, request, render_template_string

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 10

@app.errorhandler(413)
def page_not_found(e):
    #print(e)
    #print(dir(e))
    #return render_template(...)
    return 'File to big: ' + str(e)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file_image = request.files['image']
        print(dir(file_image.save))
        file_image.save(file_image.filename)
    return render_template_string('''
<form method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<button type="submit" name="button" value="send">Send</button>
</form>
''')

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

我不知道您是否可以捕获此错误并运行flash()-它可能需要更多的工作


编辑:Flask 2.x文档:Handling Application Errors

相关问题 更多 >

    热门问题