download.txt 15.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Using the download utility
==========================

The ``zc.buildout.download`` module provides a download utility that handles
the details of downloading files needed for a buildout run from the internet.
It downloads files to the local file system, using the download cache if
desired and optionally checking the downloaded files' MD5 checksum.

We setup an HTTP server that provides a file we want to download:

>>> server_data = tmpdir('sample_files')
>>> write(server_data, 'foo.txt', 'This is a foo text.')
>>> server_url = start_server(server_data)

15 16 17 18 19 20 21
We also use a fresh directory for temporary files in order to make sure that
all temporary files have been cleaned up in the end:

>>> import tempfile
>>> old_tempdir = tempfile.tempdir
>>> tempfile.tempdir = tmpdir('tmp')

22 23 24 25 26 27 28 29 30 31 32 33 34

Downloading without using the cache
-----------------------------------

If no download cache should be used, the download utility is instantiated
without any arguments:

>>> from zc.buildout.download import Download
>>> download = Download()
>>> print download.cache_dir
None

Downloading a file is achieved by calling the utility with the URL as an
35 36 37
argument. A tuple is returned that consists of the path to the downloaded copy
of the file and a boolean value indicating whether this is a temporary file
meant to be cleaned up during the same buildout run:
38

39
>>> path, is_temp = download(server_url+'foo.txt')
40 41 42 43 44 45 46 47
>>> print path
/.../buildout-...
>>> cat(path)
This is a foo text.

As we aren't using the download cache and haven't specified a target path
either, the download has ended up in a temporary file:

48 49 50
>>> is_temp
True

51 52 53 54
>>> import tempfile
>>> path.startswith(tempfile.gettempdir())
True

55 56 57 58
We are responsible for cleaning up temporary files behind us:

>>> remove(path)

59 60 61 62 63 64 65
When trying to access a file that doesn't exist, we'll get an exception:

>>> download(server_url+'not-there')
Traceback (most recent call last):
IOError: ('http error', 404, 'Not Found',
          <httplib.HTTPMessage instance at 0xa0ffd2c>)

66 67 68 69 70 71
Downloading a local file doesn't produce a temporary file but simply returns
the local file itself:

>>> download(join(server_data, 'foo.txt'))
('/sample_files/foo.txt', False)

72 73 74 75 76
We can also have the downloaded file's MD5 sum checked:

>>> try: from hashlib import md5
... except ImportError: from md5 import new as md5

77 78 79 80 81
>>> path, is_temp = download(server_url+'foo.txt',
...                          md5('This is a foo text.').hexdigest())
>>> is_temp
True
>>> remove(path)
82

83 84
>>> download(server_url+'foo.txt',
...          md5('The wrong text.').hexdigest())
85 86 87 88 89 90
Traceback (most recent call last):
ChecksumError: MD5 checksum mismatch downloading 'http://localhost/foo.txt'

The error message in the event of an MD5 checksum mismatch for a local file
reads somewhat differently:

91 92 93
>>> download(join(server_data, 'foo.txt'),
...               md5('This is a foo text.').hexdigest())
('/sample_files/foo.txt', False)
94

95 96
>>> download(join(server_data, 'foo.txt'),
...          md5('The wrong text.').hexdigest())
97 98 99 100 101 102
Traceback (most recent call last):
ChecksumError: MD5 checksum mismatch for local resource at '/sample_files/foo.txt'.

Finally, we can download the file to a specified place in the file system:

>>> target_dir = tmpdir('download-target')
103 104
>>> path, is_temp = download(server_url+'foo.txt',
...                          path=join(target_dir, 'downloaded.txt'))
105 106 107 108
>>> print path
/download-target/downloaded.txt
>>> cat(path)
This is a foo text.
109 110
>>> is_temp
False
111 112 113 114 115 116 117 118 119 120 121

Trying to download a file in offline mode will result in an error:

>>> download = Download(cache=None, offline=True)
>>> download(server_url+'foo.txt')
Traceback (most recent call last):
UserError: Couldn't download 'http://localhost/foo.txt' in offline mode.

As an exception to this rule, file system paths and URLs in the ``file``
scheme will still work:

122
>>> cat(download(join(server_data, 'foo.txt'))[0])
123
This is a foo text.
124
>>> cat(download('file:' + join(server_data, 'foo.txt'))[0])
125 126 127 128
This is a foo text.

>>> remove(path)

129

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
Downloading using the download cache
------------------------------------

In order to make use of the download cache, we need to configure the download
utility differently. To do this, we pass a directory path as the ``cache``
attribute upon instantiation:

>>> cache = tmpdir('download-cache')
>>> download = Download(cache=cache)
>>> print download.cache_dir
/download-cache/

Simple usage
~~~~~~~~~~~~

When using the cache, a file will be stored in the cache directory when it is
first downloaded. The file system path returned by the download utility points
to the cached copy:

>>> ls(cache)
150
>>> path, is_temp = download(server_url+'foo.txt')
151 152 153 154
>>> print path
/download-cache/foo.txt
>>> cat(path)
This is a foo text.
155 156
>>> is_temp
False
157 158 159 160 161

Whenever the file is downloaded again, the cached copy is used. Let's change
the file on the server to see this:

>>> write(server_data, 'foo.txt', 'The wrong text.')
162
>>> path, is_temp = download(server_url+'foo.txt')
163 164 165 166 167 168 169 170
>>> print path
/download-cache/foo.txt
>>> cat(path)
This is a foo text.

If we specify an MD5 checksum for a file that is already in the cache, the
cached copy's checksum will be verified:

171
>>> download(server_url+'foo.txt', md5('The wrong text.').hexdigest())
172 173 174 175 176 177 178 179 180
Traceback (most recent call last):
ChecksumError: MD5 checksum mismatch for cached download
               from 'http://localhost/foo.txt' at '/download-cache/foo.txt'

Trying to access another file at a different URL which has the same base name
will result in the cached copy being used:

>>> mkdir(server_data, 'other')
>>> write(server_data, 'other', 'foo.txt', 'The wrong text.')
181
>>> path, is_temp = download(server_url+'other/foo.txt')
182 183 184 185 186 187 188 189 190 191 192 193 194
>>> print path
/download-cache/foo.txt
>>> cat(path)
This is a foo text.

Given a target path for the download, the utility will provide a copy of the
file at that location both when first downloading the file and when using a
cached copy:

>>> remove(cache, 'foo.txt')
>>> ls(cache)
>>> write(server_data, 'foo.txt', 'This is a foo text.')

195 196
>>> path, is_temp = download(server_url+'foo.txt',
...                          path=join(target_dir, 'downloaded.txt'))
197 198 199 200
>>> print path
/download-target/downloaded.txt
>>> cat(path)
This is a foo text.
201 202
>>> is_temp
False
203 204 205 206 207 208
>>> ls(cache)
- foo.txt

>>> remove(path)
>>> write(server_data, 'foo.txt', 'The wrong text.')

209 210
>>> path, is_temp = download(server_url+'foo.txt',
...                          path=join(target_dir, 'downloaded.txt'))
211 212 213 214
>>> print path
/download-target/downloaded.txt
>>> cat(path)
This is a foo text.
215 216
>>> is_temp
False
217 218 219 220 221

In offline mode, downloads from any URL will be successful if the file is
found in the cache:

>>> download = Download(cache=cache, offline=True)
222
>>> cat(download(server_url+'foo.txt')[0])
223 224 225 226 227 228 229 230 231 232 233
This is a foo text.

Local resources will be cached just like any others since download caches are
sometimes used to create source distributions:

>>> remove(cache, 'foo.txt')
>>> ls(cache)

>>> write(server_data, 'foo.txt', 'This is a foo text.')
>>> download = Download(cache=cache)

234
>>> cat(download('file:' + join(server_data, 'foo.txt'), path=path)[0])
235 236 237 238 239 240
This is a foo text.
>>> ls(cache)
- foo.txt

>>> remove(cache, 'foo.txt')

241
>>> cat(download(join(server_data, 'foo.txt'), path=path)[0])
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
This is a foo text.
>>> ls(cache)
- foo.txt

>>> remove(cache, 'foo.txt')

However, resources with checksum mismatches will not be copied to the cache:

>>> download(server_url+'foo.txt', md5('The wrong text.').hexdigest())
Traceback (most recent call last):
ChecksumError: MD5 checksum mismatch downloading 'http://localhost/foo.txt'
>>> ls(cache)

>>> remove(path)

257 258 259 260 261 262
Finally, let's see what happens if the download cache to be used doesn't exist
as a directory in the file system yet:

>>> Download(cache=join(cache, 'non-existent'))(server_url+'foo.txt')
Traceback (most recent call last):
UserError: The directory:
263
'/download-cache/non-existent'
264 265
to be used as a download cache doesn't exist.

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
Using namespace sub-directories of the download cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It is common to store cached copies of downloaded files within sub-directories
of the download cache to keep some degree of order. For example, zc.buildout
stores downloaded distributions in a sub-directory named "dist". Those
sub-directories are also known as namespaces. So far, we haven't specified any
namespaces to use, so the download utility stored files directly inside the
download cache. Let's use a namespace "test" instead:

>>> download = Download(cache=cache, namespace='test')
>>> print download.cache_dir
/download-cache/test

The namespace sub-directory hasn't been created yet:

>>> ls(cache)

Downloading a file now creates the namespace sub-directory and places a copy
of the file inside it:

287
>>> path, is_temp = download(server_url+'foo.txt')
288 289 290 291 292 293 294 295
>>> print path
/download-cache/test/foo.txt
>>> ls(cache)
d test
>>> ls(cache, 'test')
- foo.txt
>>> cat(path)
This is a foo text.
296 297
>>> is_temp
False
298 299 300 301 302 303 304 305

The next time we want to download that file, the copy from inside the cache
namespace is used. To see this clearly, we put a file with the same name but
different content both on the server and in the cache's root directory:

>>> write(server_data, 'foo.txt', 'The wrong text.')
>>> write(cache, 'foo.txt', 'The wrong text.')

306
>>> path, is_temp = download(server_url+'foo.txt')
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
>>> print path
/download-cache/test/foo.txt
>>> cat(path)
This is a foo text.

>>> rmdir(cache, 'test')
>>> remove(cache, 'foo.txt')
>>> write(server_data, 'foo.txt', 'This is a foo text.')

Using a hash of the URL as the filename in the cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

So far, the base name of the downloaded file read from the URL has been used
for the name of the cached copy of the file. This may not be desirable in some
cases, for example when downloading files from different locations that have
the same base name due to some naming convention, or if the file content
depends on URL parameters. In such cases, an MD5 hash of the complete URL may
be used as the filename in the cache:

>>> download = Download(cache=cache, hash_name=True)
327
>>> path, is_temp = download(server_url+'foo.txt')
328 329 330 331 332 333 334 335 336 337 338 339
>>> print path
/download-cache/09f5793fcdc1716727f72d49519c688d
>>> cat(path)
This is a foo text.
>>> ls(cache)
- 09f5793fcdc1716727f72d49519c688d

The path was printed just to illustrate matters; we cannot know the real
checksum since we don't know which port the server happens to listen at when
the test is run, so we don't actually know the full URL of the file. Let's
check that the checksum actually belongs to the particular URL used:

340
>>> path.lower() == join(cache, md5(server_url+'foo.txt').hexdigest()).lower()
341 342 343 344 345
True

The cached copy is used when downloading the file again:

>>> write(server_data, 'foo.txt', 'The wrong text.')
346
>>> (path, is_temp) == download(server_url+'foo.txt')
347 348 349 350 351 352 353 354 355 356
True
>>> cat(path)
This is a foo text.
>>> ls(cache)
- 09f5793fcdc1716727f72d49519c688d

If we change the URL, even in such a way that it keeps the base name of the
file the same, the file will be downloaded again this time and put in the
cache under a different name:

357
>>> path2, is_temp = download(server_url+'other/foo.txt')
358 359 360 361
>>> print path2
/download-cache/537b6d73267f8f4447586989af8c470e
>>> path == path2
False
362
>>> path2.lower() == join(cache, md5(server_url+'other/foo.txt').hexdigest()).lower()
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
True
>>> cat(path)
This is a foo text.
>>> cat(path2)
The wrong text.
>>> ls(cache)
- 09f5793fcdc1716727f72d49519c688d
- 537b6d73267f8f4447586989af8c470e

>>> remove(path)
>>> remove(path2)
>>> write(server_data, 'foo.txt', 'This is a foo text.')


Using the cache purely as a fall-back
-------------------------------------

Sometimes it is desirable to try downloading a file from the net if at all
possible, and use the cache purely as a fall-back option when a server is
down or if we are in offline mode. This mode is only in effect if a download
cache is configured in the first place:

>>> download = Download(cache=cache, fallback=True)
>>> print download.cache_dir
/download-cache/

A downloaded file will be cached:

>>> ls(cache)
392
>>> path, is_temp = download(server_url+'foo.txt')
393 394 395 396
>>> ls(cache)
- foo.txt
>>> cat(cache, 'foo.txt')
This is a foo text.
397 398
>>> is_temp
False
399 400 401 402

If the file cannot be served, the cached copy will be used:

>>> remove(server_data, 'foo.txt')
403 404 405 406
>>> try: Download()(server_url+'foo.txt') # doctest: +ELLIPSIS
... except: print 'download error'
... else: print 'woops'
download error
407
>>> path, is_temp = download(server_url+'foo.txt')
408 409
>>> cat(path)
This is a foo text.
410 411
>>> is_temp
False
412 413 414 415 416

Similarly, if the file is served but we're in offline mode, we'll fall back to
using the cache:

>>> write(server_data, 'foo.txt', 'The wrong text.')
417 418 419
>>> get(server_url+'foo.txt')
'The wrong text.'

420
>>> offline_download = Download(cache=cache, offline=True, fallback=True)
421 422 423
>>> path, is_temp = offline_download(server_url+'foo.txt')
>>> print path
/download-cache/foo.txt
424 425
>>> cat(path)
This is a foo text.
426 427
>>> is_temp
False
428 429 430 431 432

However, when downloading the file normally with the cache being used in
fall-back mode, the file will be downloaded from the net and the cached copy
will be replaced with the new content:

433
>>> cat(download(server_url+'foo.txt')[0])
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
The wrong text.
>>> cat(cache, 'foo.txt')
The wrong text.

When trying to download a resource whose checksum does not match, the cached
copy will neither be used nor overwritten:

>>> write(server_data, 'foo.txt', 'This is a foo text.')
>>> download(server_url+'foo.txt', md5('The wrong text.').hexdigest())
Traceback (most recent call last):
ChecksumError: MD5 checksum mismatch downloading 'http://localhost/foo.txt'
>>> cat(cache, 'foo.txt')
The wrong text.


Configuring the download utility from buildout options
------------------------------------------------------

The configuration options explained so far derive from the build logic
implemented by the calling code. Other options configure the download utility
for use in a particular project or buildout run; they are read from the
``buildout`` configuration section. The latter can be passed directly as the
first argument to the download utility's constructor.

The location of the download cache is specified by the ``download-cache``
option:

>>> download = Download({'download-cache': cache}, namespace='cmmi')
>>> print download.cache_dir
/download-cache/cmmi

465 466 467 468 469 470 471 472 473 474 475 476 477
If the ``download-cache`` option specifies a relative path, it is understood
relative to the current working directory, or to the buildout directory if
that is given:

>>> download = Download({'download-cache': 'relative-cache'})
>>> print download.cache_dir
/sample-buildout/relative-cache/

>>> download = Download({'directory': join(sample_buildout, 'root'),
...                      'download-cache': 'relative-cache'})
>>> print download.cache_dir
/sample-buildout/root/relative-cache/

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
Keyword parameters take precedence over the corresponding options:

>>> download = Download({'download-cache': cache}, cache=None)
>>> print download.cache_dir
None

Whether to assume offline mode can be inferred from either the ``offline`` or
the ``install-from-cache`` option. As usual with zc.buildout, these options
must assume one of the values 'true' and 'false':

>>> download = Download({'offline': 'true'})
>>> download.offline
True

>>> download = Download({'offline': 'false'})
>>> download.offline
False

>>> download = Download({'install-from-cache': 'true'})
>>> download.offline
True

>>> download = Download({'install-from-cache': 'false'})
>>> download.offline
False

These two options are combined using logical 'or':

>>> download = Download({'offline': 'true', 'install-from-cache': 'false'})
>>> download.offline
True

>>> download = Download({'offline': 'false', 'install-from-cache': 'true'})
>>> download.offline
True

The ``offline`` keyword parameter takes precedence over both the ``offline``
and ``install-from-cache`` options:

>>> download = Download({'offline': 'true'}, offline=False)
>>> download.offline
False

>>> download = Download({'install-from-cache': 'false'}, offline=True)
>>> download.offline
True
524 525 526 527 528 529 530 531 532 533 534 535


Clean up
--------

We should have cleaned up all temporary files created by downloading things:

>>> ls(tempfile.tempdir)

Reset the global temporary directory:

>>> tempfile.tempdir = old_tempdir