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修改Excel数据的实例代码
Nov 01 Python
压缩包密码破解示例分享(类似典破解)
Jan 17 Python
Python中为什么要用self探讨
Apr 14 Python
python通过apply使用元祖和列表调用函数实例
May 26 Python
Python中的sort()方法使用基础教程
Jan 08 Python
Python进阶之尾递归的用法实例
Jan 31 Python
Python提取支付宝和微信支付二维码的示例代码
Feb 15 Python
python 动态迁移solr数据过程解析
Sep 04 Python
Django 解决model 反向引用中的related_name问题
May 19 Python
如何在python中实现线性回归
Aug 10 Python
Python通过队列来实现进程间通信的示例
Oct 14 Python
Python接口自动化系列之unittest结合ddt的使用教程详解
Feb 23 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 获取全局变量的代码
2011/04/21 PHP
整理的一些实用WordPress后台MySQL操作命令
2013/01/07 PHP
PHP数字金额转换成中文大写显示
2019/01/05 PHP
javascript下function声明一些小结
2007/12/28 Javascript
用户注册常用javascript代码
2009/08/29 Javascript
jquery中常用的函数和属性详细解析
2014/03/07 Javascript
JQuery Tips相关(1)----关于$.Ready()
2014/08/14 Javascript
jQuery选择器之基本选择器与层次选择器
2015/03/03 Javascript
谈谈jQuery Ajax用法详解
2015/11/27 Javascript
JavaScript中的对象继承关系
2016/08/01 Javascript
ionic2打包android时gradle无法下载的解决方法
2017/04/05 Javascript
JS实现仿饿了么在浏览器标签页失去焦点时网页Title改变
2017/06/01 Javascript
BootStrap Table前台和后台分页对JSON格式的要求
2017/06/28 Javascript
angularjs使用gulp-uglify压缩后执行报错的解决方法
2018/03/07 Javascript
使用vue根据状态添加列表数据和删除列表数据的实例
2018/09/29 Javascript
JavaScript变量提升和严格模式实例分析
2019/01/27 Javascript
NodeJs入门教程之定时器和队列
2019/03/08 NodeJs
js实现3D粒子酷炫动态旋转特效
2020/09/13 Javascript
python回调函数的使用方法
2014/01/23 Python
python实现的登录和操作开心网脚本分享
2014/07/09 Python
python中enumerate的用法实例解析
2014/08/18 Python
Python使用Flask框架获取当前查询参数的方法
2015/03/21 Python
深入理解NumPy简明教程---数组1
2016/12/17 Python
详解python调度框架APScheduler使用
2017/03/28 Python
python 递归遍历文件夹,并打印满足条件的文件路径实例
2017/08/30 Python
python3+requests接口自动化session操作方法
2018/10/13 Python
Python-while 计算100以内奇数和的方法
2019/06/11 Python
Python创建或生成列表的操作方法
2019/06/19 Python
Python Django框架url反向解析实现动态生成对应的url链接示例
2019/10/18 Python
django-利用session机制实现唯一登录的例子
2020/03/16 Python
我们在web应用开发过程中经常遇到输出某种编码的字符,如iso8859-1等,如何输出一个某种编码的字符串?
2014/03/30 面试题
司机的工作范围及职责
2013/11/13 职场文书
教育实习指导教师评语
2014/12/31 职场文书
MySQL Router实现MySQL的读写分离的方法
2021/05/27 MySQL
代码解析React中setState同步和异步问题
2021/06/03 Javascript
postgresql无序uuid性能测试及对数据库的影响
2021/06/11 PostgreSQL