-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added a refactoring to separate sending file logic from StaticRoute dispatcher #901
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ | |
import datetime | ||
import functools | ||
import io | ||
import mimetypes | ||
import os | ||
import re | ||
from urllib.parse import quote, urlencode | ||
|
@@ -16,7 +17,6 @@ | |
|
||
from . import hdrs | ||
from .errors import InvalidURL | ||
|
||
try: | ||
from asyncio import ensure_future | ||
except ImportError: | ||
|
@@ -529,3 +529,131 @@ def __exit__(self, exc_type, exc_val, exc_tb): | |
|
||
def _cancel_task(self): | ||
self._cancelled = self._task.cancel() | ||
|
||
|
||
class FileSender: | ||
""""A helper that can be used to send files. | ||
""" | ||
|
||
def __init__(self, resp_factory, chunk_size): | ||
self._response_factory = resp_factory | ||
self._chunk_size = chunk_size | ||
if bool(os.environ.get("AIOHTTP_NOSENDFILE")): | ||
self._sendfile = self._sendfile_fallback | ||
|
||
def _sendfile_cb(self, fut, out_fd, in_fd, offset, | ||
count, loop, registered): | ||
if registered: | ||
loop.remove_writer(out_fd) | ||
try: | ||
n = os.sendfile(out_fd, in_fd, offset, count) | ||
if n == 0: # EOF reached | ||
n = count | ||
except (BlockingIOError, InterruptedError): | ||
n = 0 | ||
except Exception as exc: | ||
fut.set_exception(exc) | ||
return | ||
|
||
if n < count: | ||
loop.add_writer(out_fd, self._sendfile_cb, fut, out_fd, in_fd, | ||
offset + n, count - n, loop, True) | ||
else: | ||
fut.set_result(None) | ||
|
||
@asyncio.coroutine | ||
def _sendfile_system(self, req, resp, fobj, count): | ||
""" | ||
Write `count` bytes of `fobj` to `resp` starting from `offset` using | ||
the ``sendfile`` system call. | ||
|
||
`req` should be a :obj:`aiohttp.web.Request` instance. | ||
|
||
`resp` should be a :obj:`aiohttp.web.StreamResponse` instance. | ||
|
||
`fobj` should be an open file object. | ||
|
||
`offset` should be an integer >= 0. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is no offset argument. |
||
|
||
`count` should be an integer > 0. | ||
""" | ||
transport = req.transport | ||
|
||
if transport.get_extra_info("sslcontext"): | ||
yield from self._sendfile_fallback(req, resp, fobj, count) | ||
return | ||
|
||
yield from resp.drain() | ||
|
||
loop = req.app.loop | ||
out_fd = transport.get_extra_info("socket").fileno() | ||
in_fd = fobj.fileno() | ||
fut = create_future(loop) | ||
|
||
self._sendfile_cb(fut, out_fd, in_fd, 0, count, loop, False) | ||
|
||
yield from fut | ||
|
||
@asyncio.coroutine | ||
def _sendfile_fallback(self, req, resp, fobj, count): | ||
""" | ||
Mimic the :meth:`_sendfile_system` method, but without using the | ||
``sendfile`` system call. This should be used on systems that don't | ||
support the ``sendfile`` system call. | ||
|
||
To avoid blocking the event loop & to keep memory usage low, `fobj` is | ||
transferred in chunks controlled by the `chunk_size` argument to | ||
:class:`StaticRoute`. | ||
""" | ||
chunk_size = self._chunk_size | ||
|
||
chunk = fobj.read(chunk_size) | ||
while chunk and count > chunk_size: | ||
resp.write(chunk) | ||
yield from resp.drain() | ||
count = count - chunk_size | ||
chunk = fobj.read(chunk_size) | ||
|
||
if chunk: | ||
resp.write(chunk[:count]) | ||
yield from resp.drain() | ||
|
||
if hasattr(os, "sendfile"): # pragma: no cover | ||
_sendfile = _sendfile_system | ||
else: # pragma: no cover | ||
_sendfile = _sendfile_fallback | ||
|
||
@asyncio.coroutine | ||
def send(self, req, filepath): | ||
from .web_exceptions import HTTPNotModified | ||
|
||
st = filepath.stat() | ||
|
||
modsince = req.if_modified_since | ||
if modsince is not None and st.st_mtime <= modsince.timestamp(): | ||
raise HTTPNotModified() | ||
|
||
ct, encoding = mimetypes.guess_type(str(filepath)) | ||
if not ct: | ||
ct = 'application/octet-stream' | ||
|
||
resp = self._response_factory() | ||
resp.content_type = ct | ||
if encoding: | ||
resp.headers[hdrs.CONTENT_ENCODING] = encoding | ||
resp.last_modified = st.st_mtime | ||
|
||
file_size = st.st_size | ||
|
||
resp.content_length = file_size | ||
resp.set_tcp_cork(True) | ||
try: | ||
yield from resp.prepare(req) | ||
|
||
with filepath.open('rb') as f: | ||
yield from self._sendfile(req, resp, f, file_size) | ||
|
||
finally: | ||
resp.set_tcp_nodelay(True) | ||
|
||
return resp |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is not offset argument.