flask--基础知识点--3--secure_filename()对中文的兼容

本文探讨了在Flask中使用secure_filename()函数处理中文文件名的问题,分别针对Python2和Python3环境进行了讲解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 python2

# -*- coding: utf8 -*-
import re
import os

def secure_filename(filename):
    from werkzeug._compat import text_type, PY2
    if isinstance(filename, text_type):
        from unicodedata import normalize

        filename = normalize("NFKD", filename).encode("utf-8", "ignore")
        # if not PY2:
        #     filename = filename.decode("utf-8")
        filename = filename.decode("utf-8")
    for sep in os.path.sep, os.path.altsep:
        if sep:
            filename = filename.replace(sep, " ")

    _filename_ascii_strip_re = re.compile(u"[^A-Za-z0-9_\u4e00-\u9fa5.-]")
    filename = _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
    _windows_device_files = ("CON", "AUX", "COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "LPT3", "PRN", "NUL",)
    if (
        os.name == "nt"
        and filename
        and filename.split(".")[0].upper() in _windows_device_files
    ):
        filename = "_" + filename

    return filename

filename= u"人民*/中国abc.xlsx"
filename = secure_filename(filename)
print(filename)
print(type(filename))


"""
执行结果:
[root@lighthouse ~]# python secure_filename.py 
人民_中国abc.xlsx
<type 'unicode'>
"""

2 python3

pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值