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

目录
  • 一、最近使用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不支持中文内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python实现中文转换url编码的方法

    本文实例讲述了python实现中文转换url编码的方法.分享给大家供大家参考,具体如下: 今天要处理百度贴吧的东西.想要做一个关键词的list,每次需要时,直接添加 到list里面就可以了.但是添加到list里面是中文的情况(比如'丽江'),url的地址编码却是'%E4%B8%BD%E6%B1%9F',因此需 要做一个转换.这里我们就用到了模块urllib. >>> import urllib >>> data = '丽江' >>> print dat

  • wxPython中文教程入门实例

    wxPython中文教程入门实例 wx.Window 是一个基类,许多构件从它继承.包括 wx.Frame 构件.可以在所有的子类中使用 wx.Window 的方法. wxPython的几种方法:* SetTitle( string title ) -- 设置窗口标题.只可用于框架和对话框. * SetToolTip( wx.ToolTip tip ) -- 为窗口添加提示. * SetSize( wx.Size size ) -- 设置窗口的尺寸. * SetPosition( wx.Poin

  • Python的shutil模块中文件的复制操作函数详解

    copy() chutil.copy(source, destination) shutil.copy() 函数实现文件复制功能,将 source 文件复制到 destination 文件夹中,两个参数都是字符串格式.如果 destination 是一个文件名称,那么它会被用来当作复制后的文件名称,即等于 复制 + 重命名.举例如下: >> import shutil >> import os >> os.chdir('C:\\') >> shutil.co

  • Python中使用中文的方法

    先来看看python的版本: >>> import sys >>> sys.version '2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]' (一) 用记事本创建一个文件ChineseTest.py,默认ANSI: s = "中文" print s 测试一下瞧瞧: E:\Project\Python\Test>pyt

  • python中Pycharm 输出中文或打印中文乱码现象的解决办法

    1. 确保文件开头加上以下代码: # -*- coding:utf-8 -*- 还可以加上 import sys reload(sys) sys.setdefaultencoding('utf-8') 确保以下. 如果还是没有解决中文乱码,那么进行方法2. 2. 进入setting 单击打开,单击 修改完成后,结果如下 单击"ok". 成功. 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们.

  • python 中文乱码问题深入分析

    在本文中,以'哈'来解释作示例解释所有的问题,"哈"的各种编码如下: 1. UNICODE (UTF8-16),C854: 2. UTF-8,E59388: 3. GBK,B9FE. 一.python中的str和unicode 一直以来,python中的中文编码就是一个极为头大的问题,经常抛出编码转换的异常,python中的str和unicode到底是一个什么东西呢? 在python中提到unicode,一般指的是unicode对象,例如'哈哈'的unicode对象为 u'\u54c8

  • Python使用中文正则表达式匹配指定中文字符串的方法示例

    本文实例讲述了Python使用中文正则表达式匹配指定中文字符串的方法.分享给大家供大家参考,具体如下: 业务场景: 从中文字句中匹配出指定的中文子字符串 .这样的情况我在工作中遇到非常多, 特梳理总结如下. 难点: 处理GBK和utf8之类的字符编码, 同时正则匹配Pattern中包含汉字,要汉字正常发挥作用,必须非常谨慎.推荐最好统一为utf8编码,如果不是这种最优情况,也有酌情处理. 往往一个具有普适性的正则表达式会简化程序和代码的处理,使过程简洁和事半功倍,这往往是高手和菜鸟最显著的差别.

  • python中文乱码的解决方法

    乱码原因:源码文件的编码格式为utf-8,但是window的本地默认编码是gbk,所以在控制台直接打印utf-8的字符串当然是乱码了! 解决方法:1.print mystr.decode('utf-8').encode('gbk')2.比较通用的方法: 复制代码 代码如下: import systype = sys.getfilesystemencoding()print mystr.decode('utf-8').encode(type)

  • python实现中文输出的两种方法

    本文实例讲述了python实现中文输出的两种方法.分享给大家供大家参考.具体如下: 方法一: 用encode和decode 如: import os.path import xlrd,sys Filename='/home/tom/Desktop/1234.xls' if not os.path.isfile(Filename): raise NameError,"%s is not a valid filename"%Filename bk=xlrd.open_workbook(Fi

  • 解决vscode python print 输出窗口中文乱码的问题

    一.搭建 python 环境 在 VSC 中点击 F1 键,弹出控制台,输入 ext install 界面左侧弹出扩展窗格,输入python,确认,开始搜索 下载发布者为Don Jayamanne 的 Python 插件 (下载过程中不要切换窗口,不要做其他任何操作,否则会中断下载,下载时间略长,耐心等待) 安装完毕 "文件"-"首选项"-"用户设置",打开用户配置文件settings.json,再其中大括号内输入计算机中 python.exe

随机推荐