Last active
March 30, 2021 19:58
-
-
Save bacher09/7231395 to your computer and use it in GitHub Desktop.
Example of how catch RequestEntityTooLarge exception
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
This isn't working for me. Any idea why?
I get a generic 413 error page instead of the desired flash and redirect, like it's not catching the exception:
First I tried
file = request.files.get('file')
and that didn't work either.