Completed
Push — master ( 896f50...904355 )
by Andrew
35s
created

UrlCache.get_md5()   B

Complexity

Conditions 6

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
dl 0
loc 28
rs 7.5384
c 0
b 0
f 0
1
import hashlib
2
import threading
3
from os import path
4
5
from django import template
6
7
from chat.settings import STATIC_URL, STATIC_ROOT, logging, DEBUG
8
9
register = template.Library()
10
logger = logging.getLogger(__name__)
11
12
13
class UrlCache(object):
14
	_md5_sum = {}
15
	_lock = threading.Lock()
16
17
	@classmethod
18
	def get_md5(cls, file_name):
19
		try:
20
			if DEBUG:
21
				raise KeyError("Debug mode is on, forcing calculating")
22
			else:
23
				return cls._md5_sum[file_name]
24
		except KeyError:
25
			entry_name = file_name
26
			with cls._lock:
27
				try:
28
					key = '#root#'
29
					if key in file_name:
30
						file_name = file_name.split(key,1)[1]
31
						file_path = path.join(STATIC_ROOT, entry_name.replace(key, ''))
32
						prefix = ''
33
					else:
34
						file_path = path.join(STATIC_ROOT, file_name)
35
						prefix = STATIC_URL
36
37
					md5 = cls.calc_md5(path.join(STATIC_ROOT, file_path))[:8]
38
					value = '%s%s?v=%s' % (prefix, file_name, md5)
39
					logger.info("Static file %s calculated md5 %s", file_name, md5)
40
				except:
41
					value = STATIC_URL + file_name
42
					logger.error("File %s not found, put url %s", file_name, value)
43
				cls._md5_sum[entry_name] = value
44
				return value
45
46
	@classmethod
47
	def calc_md5(cls, file_path):
48
		with open(file_path, 'rb') as fh:
49
			m = hashlib.md5()
50
			while True:
51
				data = fh.read(8192)
52
				if not data:
53
					break
54
				m.update(data)
55
			return m.hexdigest()
56
57
58
@register.simple_tag
59
def md5url(file_name):
60
	return UrlCache.get_md5(file_name)
61