Emit warning when fetching remote images failed

This commit is contained in:
Takeshi KOMIYA 2017-03-27 23:46:12 +09:00
parent a5d77a8f06
commit 25f4c004d8
3 changed files with 21 additions and 6 deletions

View File

@ -11,6 +11,7 @@
import os
from six import text_type
from docutils import nodes
from sphinx.transforms import SphinxTransform
@ -62,14 +63,22 @@ class ImageDownloader(BaseImageConverter):
ord("&"): u"/"})
ensuredir(os.path.join(imgdir, dirname))
path = os.path.join(imgdir, dirname, basename)
with open(path, 'wb') as f:
try:
r = requests.get(node['uri'])
f.write(r.content)
if r.status_code != 200:
logger.warning('Could not fetch remote image: %s [%d]' %
(node['uri'], r.status_code))
else:
with open(path, 'wb') as f:
f.write(r.content)
node['candidates'].pop('?')
node['candidates']['*'] = path
node['uri'] = path
self.app.env.images.add_file(self.env.docname, path)
node['candidates'].pop('?')
node['candidates']['*'] = path
node['uri'] = path
self.app.env.images.add_file(self.env.docname, path)
except Exception as exc:
logger.warning('Could not fetch remote image: %s [%s]' %
(node['uri'], text_type(exc)))
def setup(app):

View File

@ -17,3 +17,6 @@ test-image
.. a remote image
.. image:: https://www.python.org/static/img/python-logo.png
.. non-exist remote image
.. image:: http://example.com/NOT_EXIST.PNG

View File

@ -1051,3 +1051,6 @@ def test_latex_remote_images(app, status, warning):
result = (app.outdir / 'Python.tex').text(encoding='utf8')
assert '\\sphinxincludegraphics{{python-logo}.png}' in result
assert (app.outdir / 'python-logo.png').exists()
assert '\\sphinxincludegraphics{{NOT_EXIST}.PNG}' not in result
assert ('WARNING: Could not fetch remote image: '
'http://example.com/NOT_EXIST.PNG [404]' in warning.getvalue())