def(filename): 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(u'i contain cool xfcmlxe4uts.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 generate random filename if the function returned an empty one. .. versionadded:: 0.5 :param filename: the filename to secure """ if isinstance(filename, text_type): from unicodedata import normalize # Marek Čech、Beniardá怎样变成相对应的ascii码呢, 调用下面这句 filename = normalize('NFKD', filename).encode('ascii', 'ignore') ifnot 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('._')
# 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 = '_' + filename
classstr(object): defencode(self, encoding='utf-8', errors='strict'):# real signature unknown; restored from __doc__ """ S.encode(encoding='utf-8', errors='strict') -> bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ returnb""
具体效果如下:
1 2 3 4 5 6 7 8
"迟迟不吃饭1232233.png".encode('ascii', 'strict') # Traceback (most recent call last): # File "<input>", line 1, in <module> # UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) "迟迟不吃饭1232233.png".encode('ascii', 'replace') # b'?????1232233.png' "迟迟不吃饭1232233.png".encode('ascii', 'xmlcharrefreplace') # b'迟迟不吃饭1232233.png'
近期评论