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 31 Python
python自动化测试实例解析
Sep 28 Python
在Python的Flask框架中使用模版的入门教程
Apr 20 Python
python去除文件中空格、Tab及回车的方法
Apr 12 Python
python测试mysql写入性能完整实例
Jan 18 Python
python从list列表中选出一个数和其对应的坐标方法
Jul 20 Python
pytorch中torch.max和Tensor.view函数用法详解
Jan 03 Python
matlab中imadjust函数的作用及应用举例
Feb 27 Python
Python猴子补丁Monkey Patch用法实例解析
Mar 23 Python
python中wx模块的具体使用方法
May 15 Python
Keras SGD 随机梯度下降优化器参数设置方式
Jun 19 Python
python进度条显示之tqmd模块
Aug 22 Python
利用Matlab绘制各类特殊图形的实例代码
Flask response响应的具体使用
Python 快速验证代理IP是否有效的方法实现
Jul 15 #Python
Django路由层如何获取正确的url
Jul 15 #Python
Python实现排序方法常见的四种
Jul 15 #Python
手把手教你使用TensorFlow2实现RNN
一篇文章弄懂Python关键字、标识符和变量
You might like
phpwind中的数据库操作类
2007/01/02 PHP
PHP开发中常用的8个小技巧
2008/08/27 PHP
php中使用临时表查询数据的一个例子
2013/02/03 PHP
用PHP实现浏览器点击下载TXT文档的方法详解
2013/06/02 PHP
PHP中怎样保持SESSION不过期 原理及方案介绍
2013/08/08 PHP
php统计文章排行示例
2014/03/04 PHP
php实现用于删除整个目录的递归函数
2015/03/16 PHP
PHP检查URL包含特定字符串实例方法
2019/02/11 PHP
关于PHP5.6+版本“No input file specified”问题的解决
2019/12/11 PHP
php与阿里云短信接口接入操作案例分析
2020/05/27 PHP
IE6,IE7,IE8下使用Javascript记录光标选中范围(已补全)
2011/08/28 Javascript
javascript与jquery中跳出循环的区别总结
2013/11/04 Javascript
jquery实现手机发送验证码的倒计时代码
2014/02/12 Javascript
javaScript年份下拉列表框内容为当前年份及前后50年
2014/05/28 Javascript
详解Javascript数据类型的转换规则
2016/12/12 Javascript
AngularJS表格添加序号的方法
2017/03/03 Javascript
vue2.0结合DataTable插件实现表格动态刷新的方法详解
2017/03/17 Javascript
Bootstrap table使用方法记录
2017/08/23 Javascript
JS脚本实现网页自动秒杀点击
2018/01/11 Javascript
vue-cli项目优化方法- 缩短首屏加载时间
2018/04/01 Javascript
初步解析Python中的yield函数的用法
2015/04/03 Python
给Python的Django框架下搭建的BLOG添加RSS功能的教程
2015/04/08 Python
Python中datetime常用时间处理方法
2015/06/15 Python
python 根据正则表达式提取指定的内容实例详解
2016/12/04 Python
Python类的继承和多态代码详解
2017/12/27 Python
Python3.5 创建文件的简单实例
2018/04/26 Python
pycharm显示远程图片的实现
2019/11/04 Python
解决tensorflow添加ptb库的问题
2020/02/10 Python
英国书籍、CD、DVD和游戏的第一道德零售商:Awesome Books
2020/02/22 全球购物
行政专员岗位职责范本
2014/08/26 职场文书
夫妻分居协议书范本
2014/11/28 职场文书
公司仓管员岗位职责
2015/04/01 职场文书
2015年公司行政后勤工作总结
2015/05/20 职场文书
暑期家教宣传单
2015/07/14 职场文书
2015年女工委工作总结
2015/07/27 职场文书
Win11筛选键导致键盘失灵怎么解决? Win11关闭筛选键的技巧
2022/04/08 数码科技