Commit a26751d2 authored by Iuri de Silvio's avatar Iuri de Silvio

Make FileAdmin.base_url optional.

Add a `FileAdmin.can_download` flag to enable download of uploaded files.
If `base_url` is not defined, a `.download` route will serve uploaded files.
parent d0ca5f28
......@@ -7,7 +7,7 @@ import shutil
from operator import itemgetter
from werkzeug import secure_filename
from flask import flash, url_for, redirect, abort, request
from flask import flash, url_for, redirect, abort, request, send_from_directory
from wtforms import fields, validators
......@@ -64,13 +64,12 @@ class FileAdmin(BaseView, ActionsMixin):
"""
Simple file-management interface.
Requires two parameters:
:param path:
Path to the directory which will be managed
:param url:
Base URL for the directory. Will be used to generate
static links to the files.
:param base_url:
Optional base URL for the directory. Will be used to generate
static links to the files. If not defined, a route will be created
to serve uploaded files.
Sample usage::
......@@ -86,6 +85,11 @@ class FileAdmin(BaseView, ActionsMixin):
Is file upload allowed.
"""
can_download = True
"""
Is file download allowed.
"""
can_delete = True
"""
Is file deletion allowed.
......@@ -151,7 +155,7 @@ class FileAdmin(BaseView, ActionsMixin):
Edit template
"""
def __init__(self, base_path, base_url,
def __init__(self, base_path, base_url=None,
name=None, category=None, endpoint=None, url=None,
verify_path=True):
"""
......@@ -310,10 +314,10 @@ class FileAdmin(BaseView, ActionsMixin):
Static file path
"""
if self.is_file_editable(path):
return url_for(".edit", path=path)
route = '.edit'
else:
base_url = self.get_base_url()
return urljoin(base_url, path)
route = '.download'
return url_for(route, path=path)
def _normalize_path(self, path):
"""
......@@ -503,6 +507,27 @@ class FileAdmin(BaseView, ActionsMixin):
return self.render(self.upload_template, form=form)
@expose('/download/<path:path>')
def download(self, path=None):
"""
Download view method.
:param path:
File path.
"""
if not self.can_download:
abort(404)
base_path, directory, path = self._normalize_path(path)
# backward compatibility with base_url
base_url = self.get_base_url()
if base_url:
base_url = urljoin(url_for('.index'), base_url)
return redirect(urljoin(base_url, path))
return send_from_directory(base_path, path)
@expose('/mkdir/', methods=('GET', 'POST'))
@expose('/mkdir/<path:path>', methods=('GET', 'POST'))
def mkdir(self, path=None):
......
......@@ -83,7 +83,11 @@
</td>
{% else %}
<td>
{% if admin_view.can_download %}
<a href="{{ get_file_url(path)|safe }}">{{ name }}</a>
{% else %}
{{ name }}
{% endif %}
</td>
<td>
{{ size }}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment