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

时间:2021-09-12 09:19:47

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

一、最近使用secure_filename发现的问题

文件名是中文版的,悲剧的是中文以及其他特殊字符会被省略。

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

二、后面找到了原因

原来secure_filename()函数只返回ascii字符,非ascii字符会被过滤掉。

三、解决方案

找到secure_filename(filename)函数,修改它的源代码。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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)函数修改后的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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不支持中文内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/6984687937036222471