Python如何解决secure_filename对中文不支持问题

 更新时间:2021年07月15日 15:27:14   作者:waws520  
最近使用到了secure_filename,然后悲剧的发现中文居然不展示出来,本文就详细的介绍一下解决方法,感兴趣的可以了解一下

前言:最近使用到了secure_filename,然后悲剧的发现中文居然不展示出来,于是我慢慢的debug,终于找到问题了。

一、最近使用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继承与多重继承

    浅析python继承与多重继承

    在本篇文章中我们给大家分析了python继承与多重继承的相关知识点内容,有兴趣的读者们参考下。
    2018-09-09
  • 详解Python中的strftime()方法的使用

    详解Python中的strftime()方法的使用

    这篇文章主要介绍了详解Python中的strftime()方法的使用,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-05-05
  • Python使用Selenium爬取淘宝异步加载的数据方法

    Python使用Selenium爬取淘宝异步加载的数据方法

    今天小编就为大家分享一篇Python使用Selenium爬取淘宝异步加载的数据方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • 女友半夜加班发自拍 python男友用30行代码发现惊天秘密

    女友半夜加班发自拍 python男友用30行代码发现惊天秘密

    大家好,我是Lex 喜欢欺负超人那个Lex 女友说今晚加班,还给我发了一张照片? 我心生怀疑,就用python分析了一下照片,结果发现。。。 划重点:利用Python读取照片的GPS信息信息
    2021-08-08
  • Python 线程池用法简单示例

    Python 线程池用法简单示例

    这篇文章主要介绍了Python 线程池用法,结合简单实例形式分析了Python线程池相关使用技巧与操作注意事项,需要的朋友可以参考下
    2019-10-10
  • python3注册全局热键的实现

    python3注册全局热键的实现

    这篇文章主要介绍了python3注册全局热键的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • 利用python Pandas实现批量拆分Excel与合并Excel

    利用python Pandas实现批量拆分Excel与合并Excel

    今天带大家学习利用python Pandas实现批量拆分Excel与合并Excel,文中有非常详细的的代码示例,对正在学习python的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05
  • 在VSCode中配置Python开发环境的详细教程

    在VSCode中配置Python开发环境的详细教程

    Visual Studio Code(简称VSCode)以其强大的功能和灵活的扩展性,成为了许多开发者的首选,本文将详细介绍如何在VSCode中配置Python开发环境,需要的朋友可以参考下
    2025-04-04
  • 浅析python标准库中的glob

    浅析python标准库中的glob

    glob 文件名模式匹配,不用遍历整个目录判断每个文件是不是符合。这篇文章主要介绍了python标准库中的glob的相关知识,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2020-03-03
  • python常见的占位符总结及用法

    python常见的占位符总结及用法

    在本篇文章里小编给大家整理的是一篇关于python常见的占位符总结及用法,有兴趣的朋友们可以跟着学习参考下。
    2021-07-07

最新评论