Last active
February 8, 2018 09:57
-
-
Save xiazhibin/f158629fd024c6c453dcdd175a142047 to your computer and use it in GitHub Desktop.
secure_filename with chinese
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| _filename_gbk_strip_re = re.compile(u"^[\u4e00-\u9fa5A-Za-z0-9_.-]+$") | |
| def secure_filename(filename): | |
| 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, ' ') | |
| a = '_'.join(filename.split()) | |
| b = _filename_gbk_strip_re.sub('', a) | |
| filename = str(b).strip('._') | |
| if os.name == 'nt' and filename and \ | |
| filename.split('.')[0].upper() in _windows_device_files: | |
| filename = '_' + filename | |
| return filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment