Skip to content

Instantly share code, notes, and snippets.

@bacher09
Last active March 30, 2021 19:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bacher09/7231395 to your computer and use it in GitHub Desktop.
Save bacher09/7231395 to your computer and use it in GitHub Desktop.
Example of how catch RequestEntityTooLarge exception
from flask import Flask, request
from werkzeug.exceptions import RequestEntityTooLarge
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 # 4 Kb limit
app.config['DEBUG'] = True
@app.route("/", methods=["GET", "POST"])
def hello():
try:
# start request parsing
file = request.files['file']
except RequestEntityTooLarge as e:
# we catch RequestEntityTooLarge exception
app.logger.info(e)
return "Test"
@app.route("/exception/", methods=["GET", "POST"])
def error():
# start request parsing
request.form
raise ValueError("My error")
@app.route("/exception2/", methods=["POST"])
def error2():
# start request parsing
request.fiels
raise ValueError("My error")
@app.route("/exception3/", methods=["GET", "POST"])
def error3():
raise ValueError("My error")
@app.errorhandler(413)
def page_not_found(e):
return "Your error page for 413 status code", 413
if __name__ == "__main__":
app.run()
# create 5 Kb file
# $ dd bs=1024 count=5 if=/dev/urandom of=./testfile
# send this file to main page
# $ curl -X POST -F file=@./testfile http://127.0.0.1:5000/
# do same with other pages
@endolith
Copy link

This isn't working for me. Any idea why?

try:
    file = request.files['file']
except RequestEntityTooLarge:
    flash('File size too large.  Limit is 10 MB.')
    return redirect(url_for('upload'))

I get a generic 413 error page instead of the desired flash and redirect, like it's not catching the exception:

Request Entity Too Large
The data value transmitted exceeds the capacity limit.

First I tried file = request.files.get('file') and that didn't work either.

@endolith
Copy link

Oh it looks like the exception is being thrown earlier, as soon as I check if 'file' in request.files:?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment