12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- # Custom static_file stuff
- # Forked form bottle.py
- import os
- import bottle as b
- import time
- def custom_static_file(filename, root, request=None, custom_headers=None, mimetype='auto', download=False, charset='UTF-8'):
- """ Open a file in a safe way and return :exc:`HTTPResponse` with status
- code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
- ``Content-Length`` and ``Last-Modified`` headers are set if possible.
- Special support for ``If-Modified-Since``, ``Range`` and ``HEAD``
- requests.
- :param filename: Name or path of the file to send.
- :param root: Root path for file lookups. Should be an absolute directory
- path.
- :param mimetype: Defines the content-type header (default: guess from
- file extension)
- :param download: If True, ask the browser to open a `Save as...` dialog
- instead of opening the file with the associated program. You can
- specify a custom filename as a string. If not specified, the
- original filename is used (default: False).
- :param charset: The charset to use for files with a ``text/*``
- mime-type. (default: UTF-8)
- """
- root = os.path.abspath(root) + os.sep
- filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
- headers = dict()
- for key in custom_headers.keys():
- headers[key] = custom_headers[key]
- if not filename.startswith(root):
- return b.HTTPError(403, "Access denied.")
- if not os.path.exists(filename) or not os.path.isfile(filename):
- return b.HTTPError(404, "File does not exist.")
- if not os.access(filename, os.R_OK):
- return b.HTTPError(403, "You do not have permission to access this file.")
- if mimetype:
- if mimetype[:5] == 'text/' and charset and 'charset' not in mimetype:
- mimetype += '; charset=%s' % charset
- headers['Content-Type'] = mimetype
- if download:
- download = os.path.basename(filename if download is True else download)
- headers['Content-Disposition'] = 'attachment; filename="%s"' % download
- stats = os.stat(filename)
- headers['Content-Length'] = stats.st_size # `clen` was here, but I'm not using it
- lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
- headers['Last-Modified'] = lm
- body = '' if request.method == 'HEAD' else open(filename, 'rb')
- headers["Accept-Ranges"] = "bytes"
- #if 'HTTP_RANGE' in request.environ:
- # ranges = list(parse_range_header(request.environ['HTTP_RANGE'], clen))
- # if not ranges:
- # return HTTPError(416, "Requested Range Not Satisfiable")
- # offset, end = ranges[0]
- # headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end-1, clen)
- # headers["Content-Length"] = str(end-offset)
- # if body: body = _file_iter_range(body, offset, end-offset)
- # return HTTPResponse(body, status=206, **headers)
- return b.HTTPResponse(body, **headers)
|