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求列表交集的方法汇总
Nov 10 Python
Python挑选文件夹里宽大于300图片的方法
Mar 05 Python
在Python中使用zlib模块进行数据压缩的教程
Jun 26 Python
详解django中使用定时任务的方法
Sep 27 Python
python使用pygame框架实现推箱子游戏
Nov 20 Python
python实现一组典型数据格式转换
Dec 15 Python
python射线法判断检测点是否位于区域外接矩形内
Jun 28 Python
Python的Lambda函数用法详解
Sep 03 Python
Django admin 实现search_fields精确查询实例
Mar 30 Python
pycharm安装及如何导入numpy
Apr 03 Python
python求解汉诺塔游戏
Jul 09 Python
python实现网络五子棋
Apr 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
Zend framework处理一个http请求的流程分析
2010/02/08 PHP
PHP 之Section与Cookie使用总结
2012/09/14 PHP
PHP 5.3和PHP 5.4出现FastCGI Error解决方法
2015/02/12 PHP
PHP一致性hash分布式算法封装类定义与用法示例
2018/08/04 PHP
ThinkPHP5与单元测试PHPUnit使用详解
2020/02/23 PHP
JavaScript中“+=”的应用
2007/02/02 Javascript
Javascript 二维数组
2009/11/26 Javascript
javascript针对DOM的应用实例(一)
2012/04/15 Javascript
学习JavaScript设计模式之责任链模式
2016/01/18 Javascript
JS在浏览器中解析Base64编码图像
2017/02/09 Javascript
JS检测window.open打开的窗口是否关闭
2017/06/25 Javascript
js实现图片上传预览原理分析
2017/07/13 Javascript
node.js使用免费的阿里云ip查询获取ip所在地【推荐】
2018/09/03 Javascript
小程序实现左滑删除的效果的实例代码
2020/10/19 Javascript
[01:03:00]DOTA2上海特级锦标赛A组败者赛 EHOME VS CDEC第一局
2016/02/25 DOTA
利用pyinstaller或virtualenv将python程序打包详解
2017/03/22 Python
Python排序搜索基本算法之插入排序实例分析
2017/12/11 Python
python将.ppm格式图片转换成.jpg格式文件的方法
2018/10/27 Python
对python捕获ctrl+c手工中断程序的两种方法详解
2018/12/26 Python
pyqt5使用按钮进行界面的跳转方法
2019/06/19 Python
TensorFlow学习之分布式的TensorFlow运行环境
2020/02/05 Python
Node.js 和 Python之间该选择哪个?
2020/08/05 Python
Python类成员继承重写的实现
2020/09/16 Python
基于CSS3的animation属性实现微信拍一拍动画效果
2020/06/22 HTML / CSS
Forever 21美国官网:美国标志性快时尚品牌
2017/02/20 全球购物
美国折扣宠物药房:Total Pet Supply
2018/05/27 全球购物
马来西亚奢侈品牌购物商城:Valiram 247
2020/09/29 全球购物
实习求职信
2013/12/01 职场文书
毕业生欢送会主持词
2014/03/31 职场文书
法院信息化建设方案
2014/05/21 职场文书
硕士学位论文评语
2014/12/31 职场文书
公司文体活动总结
2015/05/07 职场文书
甲午大海战观后感
2015/06/02 职场文书
如何用PHP实现多线程编程
2021/05/26 PHP
mongodb的安装和开机自启动详细讲解
2021/08/02 MongoDB
MySQL数据库索引的最左匹配原则
2021/11/20 MySQL