| 1 |
""" |
| 2 |
This code is adapted from the Werkzeug project, under the BSD license. |
| 3 |
|
| 4 |
:copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. |
| 5 |
:license: BSD, see LICENSE for more details. |
| 6 |
""" |
| 7 |
|
| 8 |
import os |
| 9 |
import mimetypes |
| 10 |
from datetime import datetime |
| 11 |
from datetime import timezone |
| 12 |
from time import gmtime |
| 13 |
|
| 14 |
|
| 15 |
class FileWrapper(object): |
| 16 |
"""This class can be used to convert a :class:`file`-like object into |
| 17 |
an iterable. It yields `buffer_size` blocks until the file is fully |
| 18 |
read. |
| 19 |
|
| 20 |
You should not use this class directly but rather use the |
| 21 |
:func:`wrap_file` function that uses the WSGI server's file wrapper |
| 22 |
support if it's available. |
| 23 |
|
| 24 |
:param file: a :class:`file`-like object with a :meth:`~file.read` method. |
| 25 |
:param buffer_size: number of bytes for one iteration. |
| 26 |
""" |
| 27 |
|
| 28 |
def __init__(self, file, buffer_size=8192): |
| 29 |
self.file = file |
| 30 |
self.buffer_size = buffer_size |
| 31 |
|
| 32 |
def close(self): |
| 33 |
if hasattr(self.file, 'close'): |
| 34 |
self.file.close() |
| 35 |
|
| 36 |
def __iter__(self): |
| 37 |
return self |
| 38 |
|
| 39 |
def __next__(self): |
| 40 |
data = self.file.read(self.buffer_size) |
| 41 |
if data: |
| 42 |
return data |
| 43 |
raise StopIteration() |
| 44 |
|
| 45 |
|
| 46 |
def wrap_file(environ, file, buffer_size=8192): |
| 47 |
"""Wraps a file. This uses the WSGI server's file wrapper if available |
| 48 |
or otherwise the generic :class:`FileWrapper`. |
| 49 |
|
| 50 |
If the file wrapper from the WSGI server is used it's important to not |
| 51 |
iterate over it from inside the application but to pass it through |
| 52 |
unchanged. |
| 53 |
|
| 54 |
More information about file wrappers are available in :pep:`333`. |
| 55 |
|
| 56 |
:param file: a :class:`file`-like object with a :meth:`~file.read` method. |
| 57 |
:param buffer_size: number of bytes for one iteration. |
| 58 |
""" |
| 59 |
return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size) |
| 60 |
|
| 61 |
|
| 62 |
def _dump_date(d, delim): |
| 63 |
"""Used for `http_date` and `cookie_date`.""" |
| 64 |
if d is None: |
| 65 |
d = gmtime() |
| 66 |
elif isinstance(d, datetime): |
| 67 |
d = d.utctimetuple() |
| 68 |
elif isinstance(d, (int, float)): |
| 69 |
d = gmtime(d) |
| 70 |
return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % ( |
| 71 |
('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday], |
| 72 |
d.tm_mday, delim, |
| 73 |
('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', |
| 74 |
'Oct', 'Nov', 'Dec')[d.tm_mon - 1], |
| 75 |
delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec |
| 76 |
) |
| 77 |
|
| 78 |
|
| 79 |
def http_date(timestamp=None): |
| 80 |
"""Formats the time to match the RFC1123 date format. |
| 81 |
|
| 82 |
Accepts a floating point number expressed in seconds since the epoch in, a |
| 83 |
datetime object or a timetuple. All times in UTC. |
| 84 |
|
| 85 |
Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``. |
| 86 |
|
| 87 |
:param timestamp: If provided that date is used, otherwise the current. |
| 88 |
""" |
| 89 |
return _dump_date(timestamp, ' ') |
| 90 |
|
| 91 |
|
| 92 |
class StaticFileMiddleware(object): |
| 93 |
"""A WSGI middleware that provides static content for development |
| 94 |
environments. |
| 95 |
|
| 96 |
Currently the middleware does not support non ASCII filenames. If the |
| 97 |
encoding on the file system happens to be the encoding of the URI it may |
| 98 |
work but this could also be by accident. We strongly suggest using ASCII |
| 99 |
only file names for static files. |
| 100 |
|
| 101 |
The middleware will guess the mimetype using the Python `mimetype` |
| 102 |
module. If it's unable to figure out the charset it will fall back |
| 103 |
to `fallback_mimetype`. |
| 104 |
|
| 105 |
:param app: the application to wrap. If you don't want to wrap an |
| 106 |
application you can pass it :exc:`NotFound`. |
| 107 |
:param directory: the directory to serve up. |
| 108 |
:param fallback_mimetype: the fallback mimetype for unknown files. |
| 109 |
""" |
| 110 |
|
| 111 |
def __init__(self, app, directory, fallback_mimetype='text/plain'): |
| 112 |
self.app = app |
| 113 |
self.loader = self.get_directory_loader(directory) |
| 114 |
self.fallback_mimetype = fallback_mimetype |
| 115 |
|
| 116 |
def _opener(self, filename): |
| 117 |
return lambda: ( |
| 118 |
open(filename, 'rb'), |
| 119 |
datetime.fromtimestamp( |
| 120 |
os.path.getmtime(filename), |
| 121 |
tz=timezone.utc |
| 122 |
), |
| 123 |
int(os.path.getsize(filename)) |
| 124 |
) |
| 125 |
|
| 126 |
def get_directory_loader(self, directory): |
| 127 |
def loader(path): |
| 128 |
path = path or directory |
| 129 |
if path is not None: |
| 130 |
path = os.path.join(directory, path) |
| 131 |
if os.path.isfile(path): |
| 132 |
return os.path.basename(path), self._opener(path) |
| 133 |
return None, None |
| 134 |
return loader |
| 135 |
|
| 136 |
def __call__(self, environ, start_response): |
| 137 |
# sanitize the path for non unix systems |
| 138 |
cleaned_path = environ.get('PATH_INFO', '').strip('/') |
| 139 |
for sep in os.sep, os.altsep: |
| 140 |
if sep and sep != '/': |
| 141 |
cleaned_path = cleaned_path.replace(sep, '/') |
| 142 |
path = '/'.join([''] + [x for x in cleaned_path.split('/') |
| 143 |
if x and x != '..']) |
| 144 |
|
| 145 |
# attempt to find a loader for the file |
| 146 |
real_filename, file_loader = self.loader(path[1:]) |
| 147 |
if file_loader is None: |
| 148 |
return self.app(environ, start_response) |
| 149 |
|
| 150 |
# serve the file with the appropriate name if we found it |
| 151 |
guessed_type = mimetypes.guess_type(real_filename) |
| 152 |
mime_type = guessed_type[0] or self.fallback_mimetype |
| 153 |
f, mtime, file_size = file_loader() |
| 154 |
|
| 155 |
headers = [('Date', http_date())] |
| 156 |
headers.append(('Cache-Control', 'public')) |
| 157 |
headers.extend(( |
| 158 |
('Content-Type', mime_type), |
| 159 |
('Content-Length', str(file_size)), |
| 160 |
('Last-Modified', http_date(mtime)) |
| 161 |
)) |
| 162 |
|
| 163 |
start_response('200 OK', headers) |
| 164 |
return wrap_file(environ, f) |