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爬虫入门教程之点点美女图片爬虫代码分享
Sep 02 Python
Python文件及目录操作实例详解
Jun 04 Python
python实现中文分词FMM算法实例
Jul 10 Python
Python使用SocketServer模块编写基本服务器程序的教程
Jul 12 Python
如何高效使用Python字典的方法详解
Aug 31 Python
基于python实现简单日历
Jul 28 Python
python hbase读取数据发送kafka的方法
Dec 27 Python
Python里字典的基本用法(包括嵌套字典)
Feb 27 Python
python3 requests库实现多图片爬取教程
Dec 18 Python
Python面向对象封装操作案例详解
Dec 31 Python
python3 字符串知识点学习笔记
Feb 08 Python
Django使用echarts进行可视化展示的实践
Jun 10 Python
利用Matlab绘制各类特殊图形的实例代码
Flask response响应的具体使用
Python 快速验证代理IP是否有效的方法实现
Jul 15 #Python
Django路由层如何获取正确的url
Jul 15 #Python
Python实现排序方法常见的四种
Jul 15 #Python
手把手教你使用TensorFlow2实现RNN
一篇文章弄懂Python关键字、标识符和变量
You might like
PHP中的Memcache详解
2014/04/05 PHP
thinkphp框架实现数据添加和显示功能
2016/06/29 PHP
php简单实现多维数组排序的方法
2016/09/30 PHP
基于php判断客户端类型
2016/10/14 PHP
Code:findPosX 和 findPosY
2006/12/20 Javascript
jQuery的deferred对象使用详解
2011/08/20 Javascript
40款非常棒的jQuery 插件和制作教程(系列二)
2011/11/02 Javascript
js控制input框只读实现示例
2014/01/20 Javascript
js实现的复制兼容chrome和IE
2014/04/03 Javascript
js中自定义方法实现停留几秒sleep
2014/07/11 Javascript
jQuery中children()方法用法实例
2015/01/07 Javascript
js实现新年倒计时效果
2015/12/10 Javascript
懒加载实现的分页&&网站footer自适应
2016/12/21 Javascript
js实现3D图片环展示效果
2017/03/09 Javascript
js实现移动端轮播图
2020/12/21 Javascript
详解基于Vue的支持数据双向绑定的select组件
2019/09/02 Javascript
vue.js实现只能输入数字的输入框
2019/10/19 Javascript
解决vue组件销毁之后计时器继续执行的问题
2020/07/21 Javascript
[37:45]2014 DOTA2国际邀请赛中国区预选赛5.21 DT VS Orenda
2014/05/22 DOTA
python 实现堆排序算法代码
2012/06/05 Python
Python中绑定与未绑定的类方法用法分析
2016/04/29 Python
Python字符串处理实例详解
2017/05/18 Python
无法使用pip命令安装python第三方库的原因及解决方法
2018/06/12 Python
对python指数、幂数拟合curve_fit详解
2018/12/29 Python
python requests 库请求带有文件参数的接口实例
2019/01/03 Python
python定时复制远程文件夹中所有文件
2019/04/30 Python
使用Python提取文本中含有特定字符串的方法示例
2020/12/09 Python
卡西欧B级产品官方网站:Casio Outlet
2018/05/22 全球购物
乌克兰鞋类购物网站:Eobuv.com.ua
2020/11/28 全球购物
餐饮企业总经理岗位职责范文
2014/02/18 职场文书
班级安全教育实施方案
2014/02/23 职场文书
美术兴趣小组活动总结
2014/07/07 职场文书
学生安全责任书模板
2014/07/25 职场文书
2014年国庆节演讲稿
2014/09/02 职场文书
学校2016年圣诞节活动总结
2016/03/31 职场文书
springboot创建的web项目整合Quartz框架的项目实践
2022/06/21 Java/Android