Skip to content
Browse files

* move many basic functionality from pylucid plugin into filemanager

* split into BaseFilesystemBrowser and BaseFilemanager
* Update pylucid plugins
  • Loading branch information...
1 parent b092d2f commit 6dbad0e5f3baf34468ec408a60846f76758e5d71 @jedie committed Jul 3, 2012
View
223 pylucid_project/filemanager/filemanager.py
@@ -3,6 +3,9 @@
"""
filemanager
~~~~~~~~~~~
+
+ Stuff to build a app like a file manager.
+
:copyleft: 2012 by the django-tools team, see AUTHORS for more details.
:license: GNU GPL v3 or above, see LICENSE for more details.
@@ -12,128 +15,142 @@
import os
import posixpath
import urllib
+import stat
+import datetime
+import pwd
+from operator import attrgetter
+from pylucid_project.filemanager.exceptions import FilemanagerError
if __name__ == "__main__":
# For doctest only
os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
from django.conf import global_settings
global_settings.SITE_ID = 1
+from django.contrib import messages
from django.conf import settings
from django.http import Http404
from django.utils.translation import ugettext as _
-from pylucid_project.filemanager.utils import add_slash, clean_posixpath
-from pylucid_project.filemanager.exceptions import DirectoryTraversalAttack, FilemanagerError
+from pylucid_project.filemanager.filesystem_browser import BaseFilesystemBrowser
+from pylucid_project.filemanager.utils import symbolic_notation
+
+
+class BaseFilesystemObject(object):
+ def __init__(self, base_path, name, abs_path, link_path=None):
+ self.base_path = base_path # path in which this item exists
+ self.name = name # The name of the directory item
+ self.abs_path = abs_path # absolute path to this dir item
+ self.link_path = link_path # Only for links: the real path of the dir item
+
+ self.stat = os.stat(self.abs_path)
+ self.size = self.stat[stat.ST_SIZE]
+ self.mode = self.stat[stat.ST_MODE]
+ self.mtime = datetime.datetime.fromtimestamp(self.stat[stat.ST_MTIME])
+
+ self.mode_octal = oct(self.mode)
+ self.mode_symbol = symbolic_notation(self.mode)
+
+ self.uid = self.stat[stat.ST_UID]
+ self.username = pwd.getpwuid(self.uid).pw_name
+ self.gid = self.stat[stat.ST_GID]
+ self.groupname = pwd.getpwuid(self.gid).pw_name
+
+ def __repr__(self):
+ return "%s '%s' in %s" % (self.item_type, self.name, self.base_path)
+
+
+class BaseFileItem(BaseFilesystemObject):
+ is_file = True
+ is_dir = False
+ item_type = "file"
+
+
+class BaseDirItem(BaseFilesystemObject):
+ is_file = False
+ is_dir = True
+ item_type = "dir"
+
+class BaseFileLinkItem(BaseFileItem):
+ def __init__(self, *args, **kwargs):
+ super(BaseFileLinkItem, self).__init__(*args, **kwargs)
+ self.item_type = "file link to %s" % self.link_path
-class BaseFilemanager(object):
+class BaseDirLinkItem(BaseDirItem):
+ def __init__(self, *args, **kwargs):
+ super(BaseFileLinkItem, self).__init__(*args, **kwargs)
+ self.item_type = "dir link to %s" % self.link_path
+
+
+#------------------------------------------------------------------------------
+
+
+class BaseFilemanager(BaseFilesystemBrowser):
+ """
+ Base class for building a filemanager
"""
- Base class for a django app like a filemanager.
+ DIR_ITEM = BaseDirItem
+ FILE_ITEM = BaseFileItem
+ DIR_LINK_ITEM = BaseDirLinkItem
+ FILE_LINK_ITEM = BaseFileLinkItem
- >> fm = BaseFilemanager(None, BASE_PATH, "bar", "../etc/passwd")
- Traceback (most recent call last):
- ...
- DirectoryTraversalAttack: '..' found in '../etc/passwd'
+ def __init__(self, request, absolute_path, base_url, rest_url, allow_upload=False):
+ super(BaseFilemanager, self).__init__(request, absolute_path, base_url, rest_url)
- >> fm = BaseFilemanager(None, BASE_PATH, "bar", "///etc/passwd")
- Traceback (most recent call last):
- ...
- DirectoryTraversalAttack: '//' found in '///etc/passwd'
-
- >>> fm = BaseFilemanager(None, "/tmp/", "bar", "%c1%1c%c1%1c/etc/passwd")
- Traceback (most recent call last):
- ...
- Http404: Formed path '/tmp/\\xc1\\x1c\\xc1\\x1c/etc/passwd/' doesn't exist.
+ self.allow_upload = allow_upload
+ self.dir_items = self.read_dir(self.abs_path)
+
+ def read_dir(self, path):
+ dir_items = []
+ for item in os.listdir(path):
+ item_abs_path = os.path.join(self.abs_path, item)
+ link_path = None
+ if os.path.islink(item_abs_path):
+ link_path = os.readlink(item_abs_path)
+ if os.path.isdir(link_path):
+ item_class = self.DIR_LINK_ITEM
+ elif os.path.isfile(link_path):
+ item_class = self.FILE_LINK_ITEM
+ else:
+ raise NotImplemented
+ elif os.path.isdir(item_abs_path):
+ item_class = self.DIR_ITEM
+ elif os.path.isfile(item_abs_path):
+ item_class = self.FILE_ITEM
+ else:
+ messages.info(self.request, "unhandled direcory item: %r" % self.abs_path)
+ continue
+
+ instance = self.get_filesystem_item_instance(item_class, item, item_abs_path, link_path)
+ dir_items.append(instance)
+
+ # sort the dir items by name but directories first
+ # http://wiki.python.org/moin/HowTo/Sorting/#Operator_Module_Functions
+ dir_items = sorted(dir_items, key=attrgetter('item_type', 'name'))
+
+ return dir_items
- >>> fm = BaseFilemanager(None, "/tmp/", "bar", "%c0%ae%c0%ae/etc/passwd")
- Traceback (most recent call last):
- ...
- Http404: Formed path '/tmp/\\xc0\\xae\\xc0\\xae/etc/passwd/' doesn't exist.
- """
- def __init__(self, request, absolute_path, base_url, rest_url):
- """
- absolute_path - path in filesystem to the root directory
- base_url - url prefix of this filemanager instance
- rest_url - relative sub path of the current view
-
- it is assumed that 'absolute_path' and 'base_url' are internal values
- and 'rest_url' are a external given value from the requested user.
+ def get_filesystem_item_instance(self, item_class, item, item_abs_path, link_path):
"""
- self.request = request
- self.absolute_path = add_slash(absolute_path)
- self.base_url = clean_posixpath(base_url)
-
- rest_url = urllib.unquote(rest_url)
- rest_url = add_slash(rest_url)
-
- # To protect from directory traversal attack
- # https://en.wikipedia.org/wiki/Directory_traversal_attack
- clean_rest_url = clean_posixpath(rest_url)
- if clean_rest_url != rest_url:
- # path changed cause of "illegal" characters
- raise DirectoryTraversalAttack(
- "path %s is not equal to cleaned path: %s" % (repr(rest_url), repr(clean_rest_url))
- )
-
- self.rel_url = rest_url.lstrip("/")
- self.rel_path = add_slash(os.path.normpath(self.rel_url))
-
- self.abs_path = clean_posixpath(os.path.join(self.absolute_path, self.rel_path))
- self.check_path(self.absolute_path, self.abs_path)
-
- self.abs_url = posixpath.join(self.base_url, self.rel_url)
-
- if not os.path.isdir(self.abs_path):
- raise Http404("Formed path %r doesn't exist." % self.abs_path)
-
- self.breadcrumbs = self.build_breadcrumbs()
-
- def build_breadcrumbs(self):
- parts = ""
- url = self.base_url
- breadcrumbs = [{
- "name": _("index"),
- "title": _("goto 'index'"),
- "url": url
- }]
- rel_url = self.rel_url.strip("/")
- if not rel_url:
- return breadcrumbs
-
- for url_part in rel_url.split("/"):
- url += "%s/" % url_part
- parts += "%s/" % url_part
- breadcrumbs.append({
- "name": url_part,
- "title": _("goto '%s'") % parts.strip("/"),
- "url": url
- })
- return breadcrumbs
-
- def check_path(self, base_path, path):
+ Good point for overwrite, to add attributes to the filesystem items.
"""
- Simple check if the path is a sub directory of base_path.
- This must be called from external!
- """
- # Important: the path must be terminated with a slash, otherwise:
- #
- # base_path = /foo/bar
- # path = /foo/barNEW
- #
- # path starts with base_path without slashes
- #
- # which add slash:
- #
- # base_path = /foo/bar -> /foo/bar/
- # path = /foo/barNEW -> /foo/barNEW/
- # doesn't start with ---^
- #
- assert base_path.endswith(os.sep), "'base_path' must ended with a slash!"
- assert path.endswith(os.sep), "'path' must ended with a slash!"
-
- if not path.startswith(base_path):
- raise DirectoryTraversalAttack("%r doesn't start with %r" % (path, base_path))
+ instance = item_class(self.abs_path, item, item_abs_path, link_path)
+ return instance
+
+ def handle_uploaded_file(self, f):
+ if not self.allow_upload:
+ raise FilemanagerError("Upload not allowed here!")
+
+ path = os.path.join(self.abs_path, f.name)
+ destination = file(path, 'wb+')
+ for chunk in f.chunks():
+ destination.write(chunk)
+ destination.close()
+
+ messages.success(self.request,
+ "File '%s' (%i Bytes) uploaded to %s" % (f.name, f.size, self.abs_path)
+ )
if __name__ == "__main__":
View
150 pylucid_project/filemanager/filesystem_browser.py
@@ -0,0 +1,150 @@
+# coding: utf-8
+
+"""
+ filemanager
+ ~~~~~~~~~~~
+
+ :copyleft: 2012 by the django-tools team, see AUTHORS for more details.
+ :license: GNU GPL v3 or above, see LICENSE for more details.
+"""
+
+
+import os
+import posixpath
+import urllib
+import stat
+import datetime
+import pwd
+from operator import attrgetter
+
+if __name__ == "__main__":
+ # For doctest only
+ os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
+ from django.conf import global_settings
+ global_settings.SITE_ID = 1
+
+from django.contrib import messages
+from django.conf import settings
+from django.http import Http404
+from django.utils.translation import ugettext as _
+
+from pylucid_project.filemanager.utils import add_slash, clean_posixpath,\
+ symbolic_notation
+from pylucid_project.filemanager.exceptions import DirectoryTraversalAttack, FilemanagerError
+
+
+class BaseFilesystemBrowser(object):
+ """
+ Base class for a django app like a filemanager, which contains only
+ the base functionality to browse to a base path of the filesystem.
+
+ >> fm = BaseFilesystemBrowser(None, BASE_PATH, "bar", "../etc/passwd")
+ Traceback (most recent call last):
+ ...
+ DirectoryTraversalAttack: '..' found in '../etc/passwd'
+
+ >> fm = BaseFilesystemBrowser(None, BASE_PATH, "bar", "///etc/passwd")
+ Traceback (most recent call last):
+ ...
+ DirectoryTraversalAttack: '//' found in '///etc/passwd'
+
+ >>> fm = BaseFilesystemBrowser(None, "/tmp/", "bar", "%c1%1c%c1%1c/etc/passwd")
+ Traceback (most recent call last):
+ ...
+ Http404: Formed path '/tmp/\\xc1\\x1c\\xc1\\x1c/etc/passwd/' doesn't exist.
+
+ >>> fm = BaseFilesystemBrowser(None, "/tmp/", "bar", "%c0%ae%c0%ae/etc/passwd")
+ Traceback (most recent call last):
+ ...
+ Http404: Formed path '/tmp/\\xc0\\xae\\xc0\\xae/etc/passwd/' doesn't exist.
+ """
+ def __init__(self, request, absolute_path, base_url, rest_url):
+ """
+ absolute_path - path in filesystem to the root directory
+ base_url - url prefix of this filemanager instance
+ rest_url - relative sub path of the current view
+
+ it is assumed that 'absolute_path' and 'base_url' are internal values
+ and 'rest_url' are a external given value from the requested user.
+ """
+ self.request = request
+ self.absolute_path = add_slash(absolute_path)
+ self.base_url = clean_posixpath(base_url)
+
+ rest_url = urllib.unquote(rest_url)
+ rest_url = add_slash(rest_url)
+
+ # To protect from directory traversal attack
+ # https://en.wikipedia.org/wiki/Directory_traversal_attack
+ clean_rest_url = clean_posixpath(rest_url)
+ if clean_rest_url != rest_url:
+ # path changed cause of "illegal" characters
+ raise DirectoryTraversalAttack(
+ "path %s is not equal to cleaned path: %s" % (repr(rest_url), repr(clean_rest_url))
+ )
+
+ self.rel_url = rest_url.lstrip("/")
+ self.rel_path = add_slash(os.path.normpath(self.rel_url))
+
+ self.abs_path = clean_posixpath(os.path.join(self.absolute_path, self.rel_path))
+ self.check_path(self.absolute_path, self.abs_path)
+
+ self.abs_url = posixpath.join(self.base_url, self.rel_url)
+
+ if not os.path.isdir(self.abs_path):
+ raise Http404("Formed path %r doesn't exist." % self.abs_path)
+
+ self.breadcrumbs = self.build_breadcrumbs()
+
+ def build_breadcrumbs(self):
+ parts = ""
+ url = self.base_url
+ breadcrumbs = [{
+ "name": _("index"),
+ "title": _("goto 'index'"),
+ "url": url
+ }]
+ rel_url = self.rel_url.strip("/")
+ if not rel_url:
+ return breadcrumbs
+
+ for url_part in rel_url.split("/"):
+ url += "%s/" % url_part
+ parts += "%s/" % url_part
+ breadcrumbs.append({
+ "name": url_part,
+ "title": _("goto '%s'") % parts.strip("/"),
+ "url": url
+ })
+ return breadcrumbs
+
+ def check_path(self, base_path, path):
+ """
+ Simple check if the path is a sub directory of base_path.
+ This must be called from external!
+ """
+ # Important: the path must be terminated with a slash, otherwise:
+ #
+ # base_path = /foo/bar
+ # path = /foo/barNEW
+ #
+ # path starts with base_path without slashes
+ #
+ # which add slash:
+ #
+ # base_path = /foo/bar -> /foo/bar/
+ # path = /foo/barNEW -> /foo/barNEW/
+ # doesn't start with ---^
+ #
+ assert base_path.endswith(os.sep), "'base_path' must ended with a slash!"
+ assert path.endswith(os.sep), "'path' must ended with a slash!"
+
+ if not path.startswith(base_path):
+ raise DirectoryTraversalAttack("%r doesn't start with %r" % (path, base_path))
+
+if __name__ == "__main__":
+ import doctest
+ print doctest.testmod(
+# verbose=True
+ verbose=False
+ )
View
17 pylucid_project/filemanager/utils.py
@@ -111,6 +111,23 @@ def add_slash(path):
return path
+def symbolic_notation(mode):
+ """
+ Convert os.stat().st_mode values to a symbolic representation. e.g:
+
+ >>> symbolic_notation(16893) # -> 040775 -> 775
+ u'rwxrwxr-x'
+
+ >>> symbolic_notation(33204) # -> 0100664 -> 664
+ u'rw-rw-r--'
+ """
+ mode = mode & 0777 # strip "meta info"
+ chmod_symbol = u''.join(
+ mode & 0400 >> i and x or u'-' for i, x in enumerate(u'rwxrwxrwx')
+ )
+ return chmod_symbol
+
+
if __name__ == "__main__":
import doctest
print doctest.testmod(
View
168 pylucid_project/pylucid_plugins/filemanager/admin_views.py
@@ -8,7 +8,7 @@
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
-from operator import attrgetter
+
import datetime
import os
import posixpath
@@ -27,7 +27,8 @@
from pylucid_project.apps.pylucid.decorators import check_permissions, render_to
from pylucid_project.apps.pylucid_admin.admin_menu import AdminMenu
-from pylucid_project.filemanager.filemanager import BaseFilemanager
+from pylucid_project.filemanager.filemanager import BaseFilemanager, BaseDirItem,\
+ BaseFilesystemObject
from pylucid_project.pylucid_plugins.filemanager.forms import BasePathSelect, \
UploadFileForm
from pylucid_project.pylucid_plugins.filemanager.preference_forms import FilemanagerPrefForm
@@ -52,129 +53,27 @@ def install(request):
#-----------------------------------------------------------------------------
-def symbolic_notation(mode):
- """
- Convert os.stat().st_mode values to a symbolic representation. e.g:
-
- >>> symbolic_notation(16893) # -> 040775 -> 775
- u'rwxrwxr-x'
-
- >>> symbolic_notation(33204) # -> 0100664 -> 664
- u'rw-rw-r--'
- """
- mode = mode & 0777 # strip "meta info"
- chmod_symbol = u''.join(
- mode & 0400 >> i and x or u'-' for i, x in enumerate(u'rwxrwxrwx')
- )
- return chmod_symbol
-
-
-class FilesystemObject(object):
- def __init__(self, fm_instance, name, abs_path, link_path=None):
- self.fm_instance = fm_instance # Filemanager instance
- self.name = name # The name of the directory item
- self.abs_path = abs_path # absolute path to this dir item
- self.link_path = link_path # Only for links: the real path of the dir item
-
- self.base_path = self.fm_instance.abs_path # path in which this item exists
-
- self.stat = os.stat(self.abs_path)
- self.size = self.stat[stat.ST_SIZE]
- self.mode = self.stat[stat.ST_MODE]
- self.mtime = datetime.datetime.fromtimestamp(self.stat[stat.ST_MTIME])
-
- self.mode_octal = oct(self.mode)
- self.mode_symbol = symbolic_notation(self.mode)
+class Filemanager(BaseFilemanager):
+ def __init__(self, url_prefix, request, absolute_path, base_url, rest_url, allow_upload):
+ self.url_prefix = url_prefix # For building links to the files
- self.uid = self.stat[stat.ST_UID]
- self.username = pwd.getpwuid(self.uid).pw_name
- self.gid = self.stat[stat.ST_GID]
- self.groupname = pwd.getpwuid(self.gid).pw_name
-
- url_prefix = self.fm_instance.url_prefix
- if url_prefix:
- self.url = posixpath.join(url_prefix, self.fm_instance.rel_url, self.name)
-
- def __repr__(self):
- return "%s '%s' in %s" % (self.item_type, self.name, self.base_path)
-
-
-class FileItem(FilesystemObject):
- is_file = True
- item_type = "file"
+ super(Filemanager, self).__init__(request, absolute_path, base_url, rest_url, allow_upload)
-
-class DirItem(FilesystemObject):
- is_dir = True
- item_type = "dir"
- def __init__(self, *args, **kwargs):
- super(DirItem, self).__init__(*args, **kwargs)
- if self.fm_instance.url_prefix:
- self.url += "/" # add slash on all directory links
-
-
-class FileLinkItem(FileItem):
- def __init__(self, *args, **kwargs):
- super(FileLinkItem, self).__init__(*args, **kwargs)
- self.item_type = "file link to %s" % self.link_path
-
-class DirLinkItem(DirItem):
- def __init__(self, *args, **kwargs):
- super(FileLinkItem, self).__init__(*args, **kwargs)
- self.item_type = "dir link to %s" % self.link_path
-
-
-class Filemanager(BaseFilemanager):
- def __init__(self, url_prefix, *args, **kwargs):
- super(Filemanager, self).__init__(*args, **kwargs)
-
- self.url_prefix = url_prefix
-
pref_form = FilemanagerPrefForm()
self.preferences = pref_form.get_preferences()
- self.dir_items = self.read_dir(self.abs_path)
-
- def read_dir(self, path):
- dir_items = []
- for item in os.listdir(path):
- item_abs_path = os.path.join(self.abs_path, item)
- link_path = None
- if os.path.islink(item_abs_path):
- link_path = os.readlink(item_abs_path)
- if os.path.isdir(link_path):
- item_class = DirLinkItem
- elif os.path.isfile(link_path):
- item_class = FileLinkItem
- else:
- raise NotImplemented
- elif os.path.isdir(item_abs_path):
- item_class = DirItem
- elif os.path.isfile(item_abs_path):
- item_class = FileItem
- else:
- messages.info(self.request, "unhandled direcory item: %r" % self.abs_path)
- continue
-
- instance = item_class(self, item, item_abs_path, link_path)
- dir_items.append(instance)
-
- # sort the dir items by name but directories first
- # http://wiki.python.org/moin/HowTo/Sorting/#Operator_Module_Functions
- dir_items = sorted(dir_items, key=attrgetter('item_type', 'name'))
-
- return dir_items
-
- def handle_uploaded_file(self, f):
- path = os.path.join(self.abs_path, f.name)
- destination = file(path, 'wb+')
- for chunk in f.chunks():
- destination.write(chunk)
- destination.close()
-
- messages.success(self.request,
- "File '%s' (%i Bytes) uploaded to %s" % (f.name, f.size, self.abs_path)
- )
+ def get_filesystem_item_instance(self, *args, **kwargs):
+ """
+ Add url to this filesystem item, if url_prefix was set in base path config
+ """
+ instance = super(Filemanager, self).get_filesystem_item_instance(*args, **kwargs)
+
+ if self.url_prefix:
+ instance.url = posixpath.join(self.url_prefix, self.rel_url, instance.name)
+ if instance.is_dir:
+ instance.url += "/"
+
+ return instance
#-----------------------------------------------------------------------------
@@ -207,28 +106,31 @@ def filemanager(request, no, rest_url=""):
if path_form.is_valid():
base_path_no = int(path_form.cleaned_data["base_path"])
if not base_path_no == no:
- new_path = BasePathSelect.PATH_DICT[base_path_no]
+ new_path = BasePathSelect.PATH_DICT[base_path_no]["abs_base_path"]
messages.success(request, "Change base path to: '%s', ok." % new_path)
return _redirect2filemanager(base_path_no)
else:
path_form = BasePathSelect({"base_path": no})
if not path_form.is_valid():
raise Http404("Wrong page path no: %r!" % no)
- absolute_path = BasePathSelect.PATH_DICT[no]
+ path_config = BasePathSelect.PATH_DICT[no]
base_url = _reverse_filemanager_url(no)
- url_prefix = BasePathSelect.URL_DICT[no]
+ absolute_path = path_config["abs_base_path"]
+ url_prefix = path_config["url_prefix"]
+ allow_upload = path_config["allow_upload"]
- fm = Filemanager(url_prefix, request, absolute_path, base_url, rest_url)
+ fm = Filemanager(url_prefix, request, absolute_path, base_url, rest_url, allow_upload)
- if request.method == "POST" and "file" in request.FILES:
- upload_form = UploadFileForm(request.POST, request.FILES)
- if upload_form.is_valid():
- fm.handle_uploaded_file(request.FILES['file'])
- return HttpResponseRedirect(request.path)
- else:
- upload_form = UploadFileForm()
+ if allow_upload:
+ if request.method == "POST" and "file" in request.FILES:
+ upload_form = UploadFileForm(request.POST, request.FILES)
+ if upload_form.is_valid():
+ fm.handle_uploaded_file(request.FILES['file'])
+ return HttpResponseRedirect(request.path)
+ else:
+ upload_form = UploadFileForm()
dir_items = fm.dir_items
breadcrumbs = fm.breadcrumbs
@@ -242,7 +144,6 @@ def filemanager(request, no, rest_url=""):
"title": "Filemanager",
"dir_items": dir_items,
"breadcrumbs": breadcrumbs,
- "upload_form": upload_form,
"path_form": path_form,
"uid": uid,
@@ -251,6 +152,9 @@ def filemanager(request, no, rest_url=""):
"groupname": groupname,
}
+ if allow_upload:
+ context["upload_form"] = upload_form
+
return context
View
30 pylucid_project/pylucid_plugins/filemanager/forms.py
@@ -18,22 +18,38 @@
from django.utils.translation import ugettext_lazy as _
+# The base path for the filemanager. Every path is like:
BASE_PATHS = getattr(settings, "FILEMANAGER_BASE_PATHS",
(
- (settings.STATIC_ROOT, settings.STATIC_URL),
- (settings.MEDIA_ROOT, settings.MEDIA_URL),
+ {
+ # The absolute filesystem root direcotry:
+ "abs_base_path": settings.STATIC_ROOT,
+ # The url prefix for the files, if exists:
+ "url_prefix": settings.STATIC_URL,
+ # File upload to every sub path are allowed:
+ "allow_upload": True,
+ },
+ {
+ "abs_base_path": settings.MEDIA_ROOT,
+ "url_prefix": settings.MEDIA_URL,
+ "allow_upload": True,
+ },
)
)
if settings.DEBUG:
- BASE_PATHS += (
- (sys.prefix, None), # root directory of virtualenv
+ BASE_PATHS += (
+ {
+ "abs_base_path": sys.prefix, # root directory of virtualenv
+ "url_prefix": None,
+ "allow_upload": False,
+ },
+
)
class BasePathSelect(forms.Form):
- PATH_CHOICES = tuple([(no, path[0]) for no, path in enumerate(BASE_PATHS)])
- PATH_DICT = dict(PATH_CHOICES)
- URL_DICT = dict(tuple([(no, path[1]) for no, path in enumerate(BASE_PATHS)]))
+ PATH_CHOICES = tuple([(no, path["abs_base_path"]) for no, path in enumerate(BASE_PATHS)])
+ PATH_DICT = dict(tuple([(no, path) for no, path in enumerate(BASE_PATHS)]))
base_path = forms.ChoiceField(choices=PATH_CHOICES,
help_text=_("The base path for the filemanager root directory."),
View
2 pylucid_project/pylucid_plugins/filemanager/templates/filemanager/default.html
@@ -114,12 +114,14 @@
{% endfor %}
</table>
+{% if upload_form %}
<fieldset><legend>{% trans "file upload" %}</legend>
<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}
{{ upload_form.as_p }}
<input type="submit" value="upload" />
</form>
</fieldset>
+{% endif %}
<fieldset><legend>{% trans "base path" %}</legend>
<form action="" method="post">{% csrf_token %}
View
7 pylucid_project/pylucid_plugins/gallery/views.py
@@ -14,7 +14,6 @@
from glob import glob
import os
import posixpath
-from pylucid_project.filemanager.utils import add_slash
if __name__ == "__main__":
# For doctest only
@@ -30,7 +29,9 @@
from django.utils.translation import ugettext as _
# TODO: Should be moved to django-tools!
-from pylucid_project.filemanager.filemanager import BaseFilemanager, FilemanagerError
+from pylucid_project.filemanager.filemanager import FilemanagerError
+from pylucid_project.filemanager.utils import add_slash
+from pylucid_project.filemanager.filesystem_browser import BaseFilesystemBrowser
from pylucid_project.apps.pylucid.models import LogEntry
from pylucid_project.apps.pylucid.shortcuts import render_pylucid_response
@@ -76,7 +77,7 @@ def _split_suffix(filename, suffix_list):
#------------------------------------------------------------------------------
-class Gallery(BaseFilemanager):
+class Gallery(BaseFilesystemBrowser):
def __init__(self, config, *args, **kwargs):
# # use unauthorized signs from preferences
# pref_form = GalleryPrefForm()

0 comments on commit 6dbad0e

Please sign in to comment.
Something went wrong with that request. Please try again.