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 09 Python
Python基于pygame实现图片代替鼠标移动效果
Nov 11 Python
django定期执行任务(实例讲解)
Nov 03 Python
Python数据结构与算法之使用队列解决小猫钓鱼问题
Dec 14 Python
使用pandas对两个dataframe进行join的实例
Jun 08 Python
python format 格式化输出方法
Jul 16 Python
python操作openpyxl导出Excel 设置单元格格式及合并处理代码实例
Aug 27 Python
python [:3] 实现提取数组中的数
Nov 27 Python
python中adb有什么功能
Jun 07 Python
python中逻辑与或(and、or)和按位与或异或(&、|、^)区别
Aug 05 Python
matplotlib基础绘图命令之errorbar的使用
Aug 13 Python
解决python3.6用cx_Oracle库连接Oracle的问题
Dec 07 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写MySQL数据 实现代码
2009/06/15 PHP
php使用Imagick生成图片的方法
2015/07/31 PHP
利用JQuery为搜索栏增加tag提示
2009/06/22 Javascript
jquery ui dialog里调用datepicker的问题
2009/08/06 Javascript
一个javascript图片阅览组件
2010/11/09 Javascript
原来Jquery.load的方法可以一直load下去
2011/03/28 Javascript
jquery ajax方式直接提交整个表单核心代码
2013/08/15 Javascript
js监听滚动条滚动事件使得某个标签内容始终位于同一位置
2014/01/24 Javascript
解决checkbox的attr(checked)一直为undefined问题
2014/06/16 Javascript
jQuery学习笔记之 Ajax操作篇(一) - 数据加载
2014/06/23 Javascript
重写document.write实现无阻塞加载js广告(补充)
2014/12/12 Javascript
jQuery实现平滑滚动到指定锚点的方法
2015/03/20 Javascript
js事件处理程序跨浏览器解决方案
2016/03/27 Javascript
基于Jquery插件Uploadify实现实时显示进度条上传图片
2020/03/26 Javascript
BootStrap 获得轮播中的索引和当前活动的焦点对象
2017/05/11 Javascript
JavaScript运动框架 多值运动(四)
2017/05/18 Javascript
浅谈Node异步编程的机制
2017/10/18 Javascript
小程序指纹验证的实现代码
2018/12/04 Javascript
如何通过Proxy实现JSBridge模块化封装
2020/10/22 Javascript
简单的Apache+FastCGI+Django配置指南
2015/07/22 Python
Python的Flask框架中SQLAlchemy使用时的乱码问题解决
2015/11/07 Python
浅谈dataframe中更改列属性的方法
2018/07/10 Python
python抓取需要扫微信登陆页面
2019/04/29 Python
pyqt5之将textBrowser的内容写入txt文档的方法
2019/06/21 Python
Python完成哈夫曼树编码过程及原理详解
2019/07/29 Python
详解利用css3的var()实现运行时改变scss的变量值
2021/03/02 HTML / CSS
Envie de Fraise意大利:法国网上推出的孕妇装品牌
2020/10/18 全球购物
医学生个人求职信范文
2013/09/24 职场文书
年度考核自我评价
2014/01/25 职场文书
会计专业自我鉴定
2014/02/10 职场文书
《高尔基和他的儿子》教学反思
2014/04/09 职场文书
歌颂祖国的演讲稿
2014/05/04 职场文书
俞敏洪北大演讲稿
2014/05/22 职场文书
先进党组织事迹材料
2014/12/26 职场文书
婚宴新娘致辞
2015/07/28 职场文书
Python Numpy库的超详细教程
2022/04/06 Python