~ps-jenkins/friends/latestsnapshot-0.2.0daily13.05.07.1-0ubuntu1

« back to all changes in this revision

Viewing changes to friends/utils/avatar.py

  • Committer: Robert Bruce Park
  • Date: 2013-05-01 17:05:12 UTC
  • mfrom: (160.11.31 trunk-next)
  • Revision ID: robert.park@canonical.com-20130501170512-d3xrvv4vmv24k3ir
Land trunk-next into lp:friends.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
 
23
23
import os
24
 
import errno
25
24
import logging
26
25
 
27
26
from datetime import date, timedelta
29
28
from hashlib import sha1
30
29
 
31
30
from friends.utils.http import Downloader
 
31
from friends.errors import ignored
32
32
 
33
33
 
34
34
CACHE_DIR = os.path.realpath(os.path.join(
36
36
AGE_LIMIT = date.today() - timedelta(weeks=4)
37
37
 
38
38
 
39
 
try:
 
39
with ignored(FileExistsError):
40
40
    os.makedirs(CACHE_DIR)
41
 
except OSError as error:
42
 
    # It raises OSError if the dir already existed, which is fine,
43
 
    # but don't ignore other errors.
44
 
    if error.errno != errno.EEXIST:
45
 
        raise
46
41
 
47
42
 
48
43
log = logging.getLogger(__name__)
58
53
        if not url:
59
54
            return url
60
55
        local_path = Avatar.get_path(url)
61
 
        try:
62
 
            size = os.stat(local_path).st_size
63
 
            mtime = date.fromtimestamp(os.stat(local_path).st_mtime)
64
 
        except OSError as error:
65
 
            if error.errno != errno.ENOENT:
66
 
                # Some other error occurred, so propagate it up.
67
 
                raise
68
 
            # Treat a missing file as zero length.
69
 
            size = 0
 
56
        size = 0
 
57
        mtime = date.fromtimestamp(0)
 
58
 
 
59
        with ignored(FileNotFoundError):
 
60
            stat = os.stat(local_path)
 
61
            size = stat.st_size
 
62
            mtime = date.fromtimestamp(stat.st_mtime)
 
63
 
70
64
        if size == 0 or mtime < AGE_LIMIT:
71
65
            log.debug('Getting: {}'.format(url))
72
66
            image_data = Downloader(url).get_bytes()
97
91
                # The file's last modification time is earlier than the oldest
98
92
                # time we'll allow in the cache.  However, due to race
99
93
                # conditions, ignore it if the file has already been removed.
100
 
                try:
 
94
                with ignored(FileNotFoundError):
101
95
                    log.debug('Expiring: {}'.format(path))
102
96
                    os.remove(path)
103
 
                except OSError as error:
104
 
                    if error.errno != errno.ENOENT:
105
 
                        raise