handlers.py
53 lines
| 1.5 KiB
| text/x-python
|
PythonLexer
MinRK
|
r18363 | """Serve files directly from the ContentsManager.""" | |
Manuel Riel
|
r18139 | ||
# Copyright (c) IPython Development Team. | |||
# Distributed under the terms of the Modified BSD License. | |||
import os | |||
import mimetypes | |||
Manuel Riel
|
r18161 | import json | |
Manuel Riel
|
r18162 | import base64 | |
Manuel Riel
|
r18139 | from tornado import web | |
from IPython.html.base.handlers import IPythonHandler | |||
class FilesHandler(IPythonHandler): | |||
"""serve files via ContentsManager""" | |||
@web.authenticated | |||
def get(self, path): | |||
MinRK
|
r18749 | cm = self.contents_manager | |
Manuel Riel
|
r18168 | if cm.is_hidden(path): | |
Manuel Riel
|
r18139 | self.log.info("Refusing to serve hidden file, via 404 Error") | |
raise web.HTTPError(404) | |||
MinRK
|
r18749 | ||
path = path.strip('/') | |||
if '/' in path: | |||
_, name = path.rsplit('/', 1) | |||
else: | |||
name = path | |||
Thomas Kluyver
|
r18791 | model = cm.get(path) | |
Min RK
|
r18556 | ||
if self.get_argument("download", False): | |||
self.set_header('Content-Disposition','attachment; filename="%s"' % name) | |||
Manuel Riel
|
r18161 | if model['type'] == 'notebook': | |
Manuel Riel
|
r18139 | self.set_header('Content-Type', 'application/json') | |
else: | |||
cur_mime = mimetypes.guess_type(name)[0] | |||
if cur_mime is not None: | |||
self.set_header('Content-Type', cur_mime) | |||
Manuel Riel
|
r18161 | if model['format'] == 'base64': | |
Manuel Riel
|
r18162 | b64_bytes = model['content'].encode('ascii') | |
self.write(base64.decodestring(b64_bytes)) | |||
Manuel Riel
|
r18161 | elif model['format'] == 'json': | |
self.write(json.dumps(model['content'])) | |||
else: | |||
self.write(model['content']) | |||
Manuel Riel
|
r18139 | self.flush() | |
MinRK
|
r18363 | default_handlers = [ | |
(r"/files/(.*)", FilesHandler), | |||
] |