diff --git a/aiohttp/web_urldispatcher.py b/aiohttp/web_urldispatcher.py index 0c9b33ee96e..73ad55134af 100644 --- a/aiohttp/web_urldispatcher.py +++ b/aiohttp/web_urldispatcher.py @@ -143,7 +143,8 @@ def __repr__(self): class StaticRoute(Route): def __init__(self, name, prefix, directory, *, - expect_handler=None, chunk_size=256*1024): + expect_handler=None, chunk_size=256*1024, + response_factory=None): assert prefix.startswith('/'), prefix assert prefix.endswith('/'), prefix super().__init__( @@ -152,6 +153,10 @@ def __init__(self, name, prefix, directory, *, self._prefix_len = len(self._prefix) self._directory = os.path.abspath(directory) + os.sep self._chunk_size = chunk_size + if response_factory is None: + self._response_factory = StreamResponse + else: + self._response_factory = response_factory if not os.path.isdir(self._directory): raise ValueError( @@ -187,7 +192,7 @@ def handle(self, request): if not ct: ct = 'application/octet-stream' - resp = StreamResponse() + resp = self._response_factory() resp.content_type = ct if encoding: resp.headers[hdrs.CONTENT_ENCODING] = encoding @@ -407,7 +412,7 @@ def add_route(self, method, path, handler, return route def add_static(self, prefix, path, *, name=None, expect_handler=None, - chunk_size=256*1024): + chunk_size=256*1024, response_factory=None): """ Adds static files view :param prefix - url prefix @@ -418,6 +423,7 @@ def add_static(self, prefix, path, *, name=None, expect_handler=None, prefix += '/' route = StaticRoute(name, prefix, path, expect_handler=expect_handler, - chunk_size=chunk_size) + chunk_size=chunk_size, + response_factory=response_factory) self.register_route(route) return route diff --git a/docs/web_reference.rst b/docs/web_reference.rst index 5d1519ffe33..c8ecee09033 100644 --- a/docs/web_reference.rst +++ b/docs/web_reference.rst @@ -1014,7 +1014,7 @@ Router is any object that implements :class:`AbstractRouter` interface. :returns: new :class:`PlainRoute` or :class:`DynamicRoute` instance. .. method:: add_static(prefix, path, *, name=None, expect_handler=None, \ - chunk_size=256*1024) + chunk_size=256*1024, response_factory=None) Adds router for returning static files. @@ -1044,6 +1044,13 @@ Router is any object that implements :class:`AbstractRouter` interface. .. versionadded:: 0.16 + :param callable response_factory: factory to use to generate a new + response, defaults to + :class:`StreamResponse` and should + expose a compatible API. + + .. versionadded:: 0.17 + :returns: new :class:`StaticRoute` instance. .. coroutinemethod:: resolve(requst)