Last active
November 3, 2015 08:09
-
-
Save allanlei/42cfcbb8731e421a4183 to your computer and use it in GitHub Desktop.
Unicode code support for filenames using twisted.web.static.File
This file contains 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
# -*- coding: utf-8 -*- | |
from __future__ import absolute_import, division, print_function | |
from urllib import quote, unquote | |
from twisted.web import static | |
from twisted.web.static import getTypeAndEncoding, formatFileSize | |
from twisted.python import filepath | |
from twisted.python.compat import escape | |
class DirectoryLister(static.DirectoryLister): | |
def _getFilesAndDirectories(self, directory): | |
files = [] | |
dirs = [] | |
for path in directory: | |
if isinstance(path, unicode): | |
path = path.encode('utf-8') | |
url = quote(path, '/') | |
escapedPath = escape(path) | |
if not isinstance(path, unicode): | |
path = path.decode('utf-8') | |
childPath = filepath.FilePath(self.path).child(path) | |
if childPath.isdir(): | |
dirs.append({'text': escapedPath + "/", 'href': url + "/", | |
'size': '', 'type': '[Directory]', | |
'encoding': ''}) | |
else: | |
mimetype, encoding = getTypeAndEncoding(path, self.contentTypes, | |
self.contentEncodings, | |
self.defaultType) | |
try: | |
size = childPath.getsize() | |
except OSError: | |
continue | |
files.append({ | |
'text': escapedPath, "href": url, | |
'type': '[%s]' % mimetype, | |
'encoding': (encoding and '[%s]' % encoding or ''), | |
'size': formatFileSize(size)}) | |
return dirs, files | |
def render(self, request): | |
rv = static.DirectoryLister.render(self, request) | |
if isinstance(rv, unicode): | |
rv = rv.encode('utf-8') | |
return rv | |
class File(static.File): | |
def directoryListing(self): | |
return DirectoryLister(self.path, | |
self.listNames(), | |
self.contentTypes, | |
self.contentEncodings, | |
self.defaultType) | |
def getChild(self, path, request): | |
if not isinstance(path, unicode): | |
path = path.decode('utf-8') | |
return super(File, self).getChild(path, request) |
This file contains 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
# -*- coding: utf-8 -*- | |
from __future__ import absolute_import, division, print_function | |
from .static import File | |
File('/tmp/') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment