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 相关文章推荐
Python3实现的腾讯微博自动发帖小工具
Nov 11 Python
Python学习笔记(二)基础语法
Jun 06 Python
在Python程序中进行文件读取和写入操作的教程
Apr 28 Python
搞笑的程序猿:看看你是哪种Python程序员
Jun 12 Python
详解Python中的Cookie模块使用
Jul 06 Python
发布你的Python模块详解
Sep 15 Python
Python实现多条件筛选目标数据功能【测试可用】
Jun 13 Python
Python 使用matplotlib模块模拟掷骰子
Aug 08 Python
django 外键创建注意事项说明
May 20 Python
django下创建多个app并设置urls方法
Aug 02 Python
python绘制汉诺塔
Mar 01 Python
python 学习GCN图卷积神经网络
May 11 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生成的html meta和link标记在body标签里 顶部有个空行
2010/05/18 PHP
PHP+MySql+jQuery实现的"顶"和"踩"投票功能
2016/05/21 PHP
简单谈谈PHP中的trait
2017/02/25 PHP
[原创]PHP实现字节数Byte转换为KB、MB、GB、TB的方法
2017/08/31 PHP
php操作mongodb封装类与用法实例
2018/09/01 PHP
PHP simplexml_load_file()函数讲解
2019/02/03 PHP
jquery 图片截取工具jquery.imagecropper.js
2010/04/09 Javascript
基于JavaScript自定义构造函数的详解说明
2013/04/24 Javascript
js showModalDialog 弹出对话框的简单实例(子窗体)
2014/01/07 Javascript
Javascript基础教程之数据类型 (字符串 String)
2015/01/18 Javascript
JavaScript获得指定对象大小的方法
2015/07/01 Javascript
详解javascript事件冒泡
2016/01/09 Javascript
jQuery实现返回顶部功能
2016/02/23 Javascript
Vue内容分发slot(全面解析)
2017/08/19 Javascript
微信小程序中换行空格(多个空格)写法详解
2018/07/10 Javascript
Vue props 单向数据流的实现
2018/11/06 Javascript
JS中call()和apply()的功能及用法实例分析
2019/06/28 Javascript
Vue生命周期activated之返回上一页不重新请求数据操作
2020/07/26 Javascript
[02:15]2015国际邀请赛选手档案IG.Ferrari 430
2015/07/30 DOTA
python学习 流程控制语句详解
2016/06/01 Python
tensorflow学习教程之文本分类详析
2018/08/07 Python
在 Linux/Mac 下为Python函数添加超时时间的方法
2020/02/20 Python
Python实现GIF图倒放
2020/07/16 Python
Python基于argparse与ConfigParser库进行入参解析与ini parser
2021/02/02 Python
css3 flex实现div内容水平垂直居中的几种方法
2020/03/27 HTML / CSS
24个canvas基础知识小结
2014/12/17 HTML / CSS
Monki官网:斯堪的纳维亚的独立时尚品牌
2020/11/09 全球购物
Java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类
2012/02/06 面试题
杭州-飞时达软件有限公司.net笔面试
2012/04/28 面试题
硕士研究生自我鉴定范文
2013/12/27 职场文书
工作推荐信范文
2014/05/10 职场文书
Nginx使用X-Accel-Redirect实现静态文件下载的统计、鉴权、防盗链、限速等
2021/04/04 Servers
比较node.js和Deno
2021/04/27 Javascript
python装饰器代码解析
2022/03/23 Python
使用Bandicam录制鼠标指针并附带点击声音,还可以添加点击动画效果
2022/04/11 数码科技
Python使用Opencv打开笔记本电脑摄像头报错解问题及解决
2022/06/21 Python