V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
hustlzp
V2EX  ›  Python

Flask-WTForms中如何对上传文件的大小做validate?

  •  
  •   hustlzp ·
    hustlzp · 2013-12-02 22:45:05 +08:00 · 4589 次点击
    这是一个创建于 3801 天前的主题,其中的信息可能已经有所发展或是发生改变。
    WTF没有提供任何File相关的validator,Flask-WTF提供了FileAllow和FileRequire。

    问下大家如何对上传文件的大小做验证?

    Nginx可以配置client_max_body_size的最大HTTP body的限制,超出限制则报413 Request Entity Too Large错误,可以在Flask中写一个413错误页面。

    那么如何做小于20M的文件(比如5M)限制检验?

    Werkzeug的FileStorage中有个content_length属性,不过文档中有个说明:Usually not available,不太懂...为什么会出现not available的情况...:

    http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage

    目前只想到去读取request中的Content-Length的长度,如果减去1M(除文件之外的其他部分的大小,这里只是预估一下)仍然大于5M的话,就判定是超出5M的。

    各位大哥给点建议?
    4 条回复    1970-01-01 08:00:00 +08:00
    sillyousu
        1
    sillyousu  
       2013-12-03 08:32:48 +08:00 via Android
    content_len 在http协议里面就是没有规定一定要有的。所以这个有的时候会没有。另外就算有的话你敢信?

    小20M看起来楼主是又办法了,你是张玩小于20且大于5么?

    另外nginx的一些插件做上文件传会好一些。
    hustlzp
        2
    hustlzp  
    OP
       2013-12-03 09:29:11 +08:00
    @sillyousu
    原来如此...感谢~

    对,我想给5M-20M的文件上传给一个提示。

    大于20M只能直接跳转预设的413页面...
    sillyousu
        3
    sillyousu  
       2013-12-03 10:00:49 +08:00   ❤️ 1
    @hustlzp

    试试这个 http://www.grid.net.ru/nginx/upload.en.html

    这个模块不能禁止小于1M的文件上传,不过你可以在flask做到这件事情。
    因为他会把post表单里面file 那个field 替换成 文件路径 文件大小 文件md5 checksum 等fields

    囧 刚才的回复在手机写错漏很多。
    hustlzp
        4
    hustlzp  
    OP
       2013-12-03 10:11:49 +08:00
    @sillyousu 大谢啊!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1362 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 17:29 · PVG 01:29 · LAX 10:29 · JFK 13:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.