Skip to content

Instantly share code, notes, and snippets.

@xiazhibin
Last active February 8, 2018 09:57
Show Gist options
  • Save xiazhibin/f158629fd024c6c453dcdd175a142047 to your computer and use it in GitHub Desktop.
Save xiazhibin/f158629fd024c6c453dcdd175a142047 to your computer and use it in GitHub Desktop.
secure_filename with chinese
_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