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

查看:1168
本文介绍了是否有可能在每个路由的基础上限制Flask POST数据大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以在Flask中设置请求大小的整体限制: p>

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

但是我想确保一个特定的路由不会接受超过一定大小的POST数据。



这可能吗?

解决方案

您需要检查这个特定的路线本身;你可以随时测试内容的长度; request.content_length None 或者一个整数值:

  cl = request.content_length 
如果cl不是None且cl> 3 * 1024 * 1024:
abort(413)

在访问表单或文件数据请求。



你可以把它变成你的视图的装饰器:

  from functools import 
from flask import request,abort

$ b def limit_content_length(max_length):
def decorator(f):
@wraps(f)
def包装(* args,** kwargs):
cl = request.content_length
如果cl不是None并且cl> max_length:
abort(413)
返回f(* args,** kwargs)
返回包装
返回装饰器


$ b

)然后使用这个:
$ b $ pre $ @ app.route(' / ...')
@limit_content_length(3 * 1024 * 1024)
def your_view():
#...

这实际上是Flask做的事情;当您尝试访问请求数据时,首先检查Content-Length标头,然后再尝试解析请求主体。使用装饰器或手动检查你只是做了相同的测试,但在视图生命周期的一点点。


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.

这篇关于是否有可能在每个路由的基础上限制Flask POST数据大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆