Python如何解决secure_filename对中文不支持问题


Posted in Python onJuly 16, 2021

前言:最近使用到了secure_filename,然后悲剧的发现中文居然不展示出来,于是我慢慢的debug,终于找到问题了。

一、最近使用secure_filename发现的问题

文件名是中文版的,悲剧的是中文以及其他特殊字符会被省略。

Python如何解决secure_filename对中文不支持问题

二、后面找到了原因

原来secure_filename()函数只返回ASCII字符,非ASCII字符会被过滤掉。

三、解决方案

找到secure_filename(filename)函数,修改它的源代码。

secure_filename(filename)函数源代码:
def secure_filename(filename: str) -> str:
    r"""Pass it a filename and it will return a secure version of it.  This
    filename can then safely be stored on a regular file system and passed
    to :func:`os.path.join`.  The filename returned is an ASCII only string
    for maximum portability.

    On windows systems the function also makes sure that the file is not
    named after one of the special device files.

    >>> secure_filename("My cool movie.mov")
    'My_cool_movie.mov'
    >>> secure_filename("../../../etc/passwd")
    'etc_passwd'
    >>> secure_filename('i contain cool \xfcml\xe4uts.txt')
    'i_contain_cool_umlauts.txt'

    The function might return an empty filename.  It's your responsibility
    to ensure that the filename is unique and that you abort or
    generate a random filename if the function returned an empty one.

    .. versionadded:: 0.5

    :param filename: the filename to secure
    """
    filename = unicodedata.normalize("NFKD", filename)
    filename = filename.encode("ascii", "ignore").decode("ascii")

    for sep in os.path.sep, os.path.altsep:
        if sep:
            filename = filename.replace(sep, " ")
    filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip(
        "._"
    )

    # on nt a couple of special files are present in each folder.  We
    # have to ensure that the target file is not such a filename.  In
    # this case we prepend an underline
    if (
        os.name == "nt"
        and filename
        and filename.split(".")[0].upper() in _windows_device_files
    ):
        filename = f"_{filename}"

    return filename

secure_filename(filename)函数修改后的代码:

def secure_filename(filename: str) -> str:
    r"""Pass it a filename and it will return a secure version of it.  This
    filename can then safely be stored on a regular file system and passed
    to :func:`os.path.join`.  The filename returned is an ASCII only string
    for maximum portability.

    On windows systems the function also makes sure that the file is not
    named after one of the special device files.

    >>> secure_filename("My cool movie.mov")
    'My_cool_movie.mov'
    >>> secure_filename("../../../etc/passwd")
    'etc_passwd'
    >>> secure_filename('i contain cool \xfcml\xe4uts.txt')
    'i_contain_cool_umlauts.txt'

    The function might return an empty filename.  It's your responsibility
    to ensure that the filename is unique and that you abort or
    generate a random filename if the function returned an empty one.

    .. versionadded:: 0.5

    :param filename: the filename to secure
    """
    filename = unicodedata.normalize("NFKD", filename)
    filename = filename.encode("utf8", "ignore").decode("utf8")   # 编码格式改变

    for sep in os.path.sep, os.path.altsep:
        if sep:
            filename = filename.replace(sep, " ")
    _filename_ascii_add_strip_re = re.compile(r'[^A-Za-z0-9_\u4E00-\u9FBF\u3040-\u30FF\u31F0-\u31FF.-]')
    filename = str(_filename_ascii_add_strip_re.sub('', '_'.join(filename.split()))).strip('._')             # 添加新规则

    # on nt a couple of special files are present in each folder.  We
    # have to ensure that the target file is not such a filename.  In
    # this case we prepend an underline
    if (
        os.name == "nt"
        and filename
        and filename.split(".")[0].upper() in _windows_device_files
    ):
        filename = f"_{filename}"

    return filename

四、效果展示

我们很清楚的看到了效果,目前是支持中文的

Python如何解决secure_filename对中文不支持问题

到此这篇关于Python如何解决secure_filename对中文不支持问题的文章就介绍到这了,更多相关Python secure_filename不支持中文内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python实现全局变量的两个解决方法
Jul 03 Python
Python动态加载模块的3种方法
Nov 22 Python
基于Django的python验证码(实例讲解)
Oct 23 Python
Python解析命令行读取参数--argparse模块使用方法
Jan 23 Python
Python实现去除列表中重复元素的方法小结【4种方法】
Apr 27 Python
解决tensorflow测试模型时NotFoundError错误的问题
Jul 27 Python
python pandas库的安装和创建
Jan 10 Python
浅谈Pycharm中的Python Console与Terminal
Jan 17 Python
Python进阶:生成器 懒人版本的迭代器详解
Jun 29 Python
在jupyter notebook 添加 conda 环境的操作详解
Apr 10 Python
Python如何合并多个字典或映射
Jul 24 Python
Python3爬虫关于代理池的维护详解
Jul 30 Python
利用Matlab绘制各类特殊图形的实例代码
Flask response响应的具体使用
Python 快速验证代理IP是否有效的方法实现
Jul 15 #Python
Django路由层如何获取正确的url
Jul 15 #Python
Python实现排序方法常见的四种
Jul 15 #Python
手把手教你使用TensorFlow2实现RNN
一篇文章弄懂Python关键字、标识符和变量
You might like
第十二节 类的自动加载 [12]
2006/10/09 PHP
php字符串截取中文截取2,单字节截取模式
2007/12/10 PHP
将博客园(cnblogs.com)数据导入到wordpress的代码
2013/01/06 PHP
3Z版基于jquery的图片复选框(asp.net+jquery)
2010/04/12 Javascript
jQuery Tips 为AJAX回调函数传递额外参数的方法
2010/12/28 Javascript
jQuery fadeTo方法调整图片的透明度使用介绍
2013/05/06 Javascript
jQuery 借助插件Lavalamp实现导航条动态美化效果
2013/09/27 Javascript
两个数组去重的JS代码
2013/12/04 Javascript
JavaScript对象学习小结
2015/09/02 Javascript
javascript实现tab切换的四种方法
2015/11/05 Javascript
JavaScript进阶练习及简单实例分析
2016/06/03 Javascript
JS实现图片剪裁并预览效果
2016/08/12 Javascript
JS公共小方法之判断对象是否为domElement的实例
2016/11/25 Javascript
webpack4 CSS Tree Shaking的使用
2018/09/03 Javascript
脚手架vue-cli工程webpack的基本用法详解
2018/09/29 Javascript
vue使用原生js实现滚动页面跟踪导航高亮的示例代码
2018/10/25 Javascript
Jquery获取radio选中值实例总结
2019/01/17 jQuery
使用jquery-easyui的布局layout写后台管理页面的代码详解
2019/06/19 jQuery
在elementui中Notification组件添加点击事件实例
2020/11/11 Javascript
python抓取豆瓣图片并自动保存示例学习
2014/01/10 Python
Python中使用语句导入模块或包的机制研究
2015/03/30 Python
Python缩进和冒号详解
2016/06/01 Python
Python yield 使用方法浅析
2017/05/20 Python
python 反向输出字符串的方法
2018/07/16 Python
Python线性拟合实现函数与用法示例
2018/12/13 Python
python GUI库图形界面开发之PyQt5单选按钮控件QRadioButton详细使用方法与实例
2020/02/28 Python
Python轻量级web框架bottle使用方法解析
2020/06/13 Python
Python sqlalchemy时间戳及密码管理实现代码详解
2020/08/01 Python
涂鸦板简单实现 Html5编写属于自己的画画板
2016/07/05 HTML / CSS
Html5实现首页动态视频背景的示例代码
2019/09/25 HTML / CSS
描述JSP和Servlet的区别、共同点、各自应用的范围
2012/10/02 面试题
明信片寄语大全
2014/04/08 职场文书
体育系毕业生自荐信
2014/06/28 职场文书
单位委托函范文
2015/01/29 职场文书
同意离婚答辩状
2015/05/22 职场文书
shell进度条追踪指令执行时间的场景分析
2022/06/16 Servers