-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload_handlers.py
58 lines (50 loc) · 2.34 KB
/
upload_handlers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import logging
from django.conf import settings
from django.core.cache import cache
from django.core.files.uploadhandler import MemoryFileUploadHandler
class UploadProgressCachedHandler(MemoryFileUploadHandler):
"""
Tracks progress for file uploads.
The http post request must contain a query parameter, 'X-Progress-ID',
which should contain a unique string to identify the upload to be tracked.
"""
def __init__(self, request=None):
super(UploadProgressCachedHandler, self).__init__(request)
self.progress_id = None
self.cache_key = None
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
logger = logging.getLogger('uploaddemo.upload_handlers.UploadProgressCachedHandler.handle_raw_input')
self.content_length = content_length
if 'X-Progress-ID' in self.request.GET:
self.progress_id = self.request.GET['X-Progress-ID']
if self.progress_id:
self.cache_key = "%s_%s" % (self.request.META['REMOTE_ADDR'], self.progress_id )
cache.set(self.cache_key, {
'state': 'uploading',
'size': self.content_length,
'received': 0
})
if settings.DEBUG:
logger.debug('Initialized cache with %s' % cache.get(self.cache_key))
else:
logging.getLogger('UploadProgressCachedHandler').error("No progress ID.")
def new_file(self, field_name, file_name, content_type, content_length, charset=None):
pass
def receive_data_chunk(self, raw_data, start):
logger = logging.getLogger('uploaddemo.upload_handlers.UploadProgressCachedHandler.receive_data_chunk')
if self.cache_key:
data = cache.get(self.cache_key)
if data:
data['received'] += self.chunk_size
cache.set(self.cache_key, data)
if settings.DEBUG:
logger.debug('Updated cache with %s' % data)
return raw_data
def file_complete(self, file_size):
pass
def upload_complete(self):
logger = logging.getLogger('uploaddemo.upload_handlers.UploadProgressCachedHandler.upload_complete')
if settings.DEBUG:
logger.debug('Upload complete for %s' % self.cache_key)
if self.cache_key:
cache.delete(self.cache_key)