def file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None): """Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): return wsgi.file_response(request, "<filepath>") :param request: Wsgi request :param filepath: full path of file to serve :param block: Optional block size (deafult 1MB) :param status_code: Optional status code (default 200) :return: a :class:`~.WsgiResponse` object """ file_wrapper = request.get('wsgi.file_wrapper') if os.path.isfile(filepath): response = request.response info = os.stat(filepath) size = info[stat.ST_SIZE] modified = info[stat.ST_MTIME] header = request.get('HTTP_IF_MODIFIED_SINCE') if not was_modified_since(header, modified, size): response.status_code = 304 else: if not content_type: content_type, encoding = mimetypes.guess_type(filepath) file = open(filepath, 'rb') response.headers['content-length'] = str(size) response.content = file_wrapper(file, block) response.content_type = content_type response.encoding = encoding if status_code: response.status_code = status_code else: response.headers["Last-Modified"] = http_date(modified) if cache_control: etag = digest('modified: %d - size: %d' % (modified, size)) cache_control(response.headers, etag=etag) return response raise Http404
def serve_file(self, environ, fullpath): # Respect the If-Modified-Since header. statobj = os.stat(fullpath) content_type, encoding = mimetypes.guess_type(fullpath) content_type = content_type or self.DEFAULT_CONTENT_TYPE if not self.was_modified_since(environ.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return wsgi.WsgiResponse(status=304, content_type=content_type, encoding=encoding) contents = open(fullpath, 'rb').read() response = wsgi.WsgiResponse(content=contents, content_type=content_type, encoding=encoding) response.headers["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) return response
def serve_file(self, request, fullpath): # Respect the If-Modified-Since header. statobj = os.stat(fullpath) content_type, encoding = mimetypes.guess_type(fullpath) response = request.response if content_type: response.content_type = content_type response.encoding = encoding if not self.was_modified_since( request.environ.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): response.status_code = 304 else: response.content = open(fullpath, 'rb').read() response.headers["Last-Modified"] = http_date( statobj[stat.ST_MTIME]) return response
def test_http_date(self): now = time.time() fmt = http_date(now) self.assertTrue(fmt.endswith(' GMT')) self.assertEqual(fmt[3:5], ', ')
def test_http_date(self): now = time.time() fmt = http_date(now) self.assertTrue(fmt.endswith(" GMT")) self.assertEqual(fmt[3:5], ", ")
def test_http_date(self): now = time.time() fmt = httpurl.http_date(now) self.assertTrue(fmt.endswith(' GMT')) self.assertEqual(fmt[3:5], ', ')