flask secure_filename無法獲取中文


參考博客

因為該方法采用ascii與正則匹配字母和數字,所以無法匹配中文等其他字符

所以需要修改源碼。找到Lib\site-packages\werkzeug\utils的secure_filename方法

初始代碼:

_filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9_.-]")#原始正則

if
isinstance(filename, text_type): from unicodedata import normalize filename = normalize("NFKD", filename).encode("ascii", "ignore") if not PY2: filename = filename.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( "._" )

 

 

改后的代碼:

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")
    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.-]')#新的正則
    filename = str(_filename_ascii_add_strip_re.sub("", "_".join(filename.split()))).strip(
        "._"
    )

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM