是否有可能在每个路由的基础上限制Flask POST数据大小?(Is it possible to limit Flask POST data size on a per-route basis?)

mac2024-05-21  30

I am aware it is possible to set an overall limit on request size in Flask with:

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

BUT I want to ensure that one specific route will not accept POST data over a certain size.

Is this possible?

解决方案

You'll need to check this for the specific route itself; you can always test the content length; request.content_length is either None or an integer value:

cl = request.content_length if cl is not None and cl > 3 * 1024 * 1024: abort(413)

Do this before accessing form or file data on the request.

You can make this into a decorator for your views:

from functools import wraps from flask import request, abort def limit_content_length(max_length): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): cl = request.content_length if cl is not None and cl > max_length: abort(413) return f(*args, **kwargs) return wrapper return decorator

then use this as:

@app.route('/...') @limit_content_length(3 * 1024 * 1024) def your_view(): # ...

This is essentially what Flask does; when you try to access request data, the Content-Length header is checked first before attempting to parse the request body. With the decorator or manual check you just made the same test, but a little earlier in the view lifecycle.

最新回复(0)