|
1
|
|
|
''' |
|
2
|
|
|
Helper functions for the view implementations. |
|
3
|
|
|
''' |
|
4
|
|
|
|
|
5
|
|
|
import io |
|
6
|
|
|
import zipfile |
|
7
|
|
|
|
|
8
|
|
|
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin |
|
9
|
|
|
from django.views.generic import DetailView |
|
10
|
|
|
from django.http import FileResponse, HttpResponse |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
class StaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin): |
|
14
|
|
|
''' |
|
15
|
|
|
Ensures that the user is logged in and has backend rights. |
|
16
|
|
|
''' |
|
17
|
|
|
def test_func(self): |
|
18
|
|
|
return self.request.user.is_staff |
|
19
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
class BinaryDownloadMixin(object): |
|
22
|
|
|
f = None |
|
23
|
|
|
fname = None |
|
24
|
|
|
|
|
25
|
|
|
def get(self, request, *args, **kwargs): |
|
26
|
|
|
super().get(request, *args, **kwargs) |
|
27
|
|
|
assert(self.f is not None) |
|
28
|
|
|
assert(self.fname is not None) |
|
29
|
|
|
response = HttpResponse(self.f, content_type='application/binary') |
|
30
|
|
|
response['Content-Disposition'] = 'attachment; filename="%s"' % self.fname |
|
31
|
|
|
return response |
|
32
|
|
|
|
|
33
|
|
|
|
|
34
|
|
|
class ZipDownloadDetailView(DetailView): |
|
35
|
|
|
''' |
|
36
|
|
|
Specialized DetailView base class for ZIP downloads. |
|
37
|
|
|
|
|
38
|
|
|
Only intended as base class. |
|
39
|
|
|
''' |
|
40
|
|
|
def get(self, request, *args, **kwargs): |
|
41
|
|
|
super().get(request, *args, **kwargs) |
|
42
|
|
|
output = io.BytesIO() |
|
43
|
|
|
z = zipfile.ZipFile(output, 'w') |
|
44
|
|
|
file_name = self.fill_zip_file(z) |
|
45
|
|
|
z.close() |
|
46
|
|
|
# go back to start in ZIP file so that Django can deliver it |
|
47
|
|
|
output.seek(0) |
|
48
|
|
|
response = FileResponse( |
|
49
|
|
|
output, content_type="application/x-zip-compressed") |
|
50
|
|
|
response['Content-Disposition'] = 'attachment; filename=%s.zip' % file_name |
|
51
|
|
|
return response |
|
52
|
|
|
|
|
53
|
|
|
def fill_zip_file(self, z): |
|
54
|
|
|
''' |
|
55
|
|
|
Function that fills the given ZIP file instance with data. |
|
56
|
|
|
To be implemented by derived class. |
|
57
|
|
|
|
|
58
|
|
|
Parameters: |
|
59
|
|
|
z: ZIP file instance |
|
60
|
|
|
|
|
61
|
|
|
Returns: File name for the download |
|
62
|
|
|
''' |
|
63
|
|
|
raise NotImplementedError |
|
64
|
|
|
|