Skip to content

Commit 8fb6285

Browse files
author
João Paulo Dubas
committed
Separate serialiazation and json response from view processing.
1 parent 2ec7f80 commit 8fb6285

File tree

3 files changed

+86
-54
lines changed

3 files changed

+86
-54
lines changed

fileupload/response.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# encoding: utf-8
2+
from django.http import HttpResponse
3+
from django.utils import simplejson
4+
5+
MIMEANY = '*/*'
6+
MIMEJSON = 'application/json'
7+
MIMETEXT = 'text/plain'
8+
9+
10+
def response_mimetype(request):
11+
"""response_mimetype -- Return a proper response mimetype, accordingly to
12+
what the client accepts, as available in the `HTTP_ACCEPT` header.
13+
14+
request -- a HttpRequest instance.
15+
16+
"""
17+
can_json = MIMEJSON in request.META['HTTP_ACCEPT']
18+
can_json |= MIMEANY in request.META['HTTP_ACCEPT']
19+
return MIMEJSON if can_json else MIMETEXT
20+
21+
22+
class JSONResponse(HttpResponse):
23+
"""JSON response class."""
24+
def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
25+
json_opts = json_opts if isinstance(json_opts, dict) else {}
26+
content = simplejson.dumps(obj, **json_opts)
27+
super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)

fileupload/serialize.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# encoding: utf-8
2+
import mimetypes
3+
import re
4+
from django.core.urlresolvers import reverse
5+
6+
7+
def order_name(name):
8+
"""order_name -- Limit the name to 20 chars length, and convert to a
9+
ellipsed string.
10+
11+
name -- text to be limited.
12+
13+
"""
14+
name = re.sub (r'^.*/', '', name)
15+
if len(name)>20:
16+
return name[:10] + "..." + name[-7:]
17+
else:
18+
return name
19+
20+
21+
def serialize(instance):
22+
"""serialize -- Serialize a Picture instance into a `json` object.
23+
24+
instance -- Picture instance
25+
"""
26+
return {
27+
'url': instance.file.url,
28+
'name': order_name(instance.file.name),
29+
'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png',
30+
'thumbnailUrl': instance.file.url,
31+
'size': instance.file.size,
32+
'deleteUrl': reverse('upload-delete', args=[instance.pk]),
33+
'deleteType': 'DELETE',
34+
}
35+
36+

fileupload/views.py

+23-54
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,55 @@
1-
from fileupload.models import Picture
2-
from django.views.generic import CreateView, DeleteView
1+
# encoding: utf-8
2+
from django.views.generic import CreateView, DeleteView, View
3+
from .models import Picture
4+
from .response import JSONResponse, response_mimetype
5+
from .serialize import serialize
36

4-
from django.http import HttpResponse, HttpResponseRedirect
5-
from django.utils import simplejson
6-
from django.core.urlresolvers import reverse
7-
8-
from django.conf import settings
9-
import re
10-
11-
def response_mimetype(request):
12-
if "application/json" in request.META['HTTP_ACCEPT']:
13-
return "application/json"
14-
else:
15-
return "text/plain"
16-
17-
def orderName(name):
18-
name = re.sub (r'^.*/', '', name)
19-
if len(name)>20:
20-
return name[:10] + "..." + name[-7:]
21-
else:
22-
return name
237

248
class PictureCreateView(CreateView):
259
model = Picture
2610

2711
def form_valid(self, form):
2812
self.object = form.save()
29-
f = self.request.FILES.get('file')
30-
files = [{
31-
'url': self.object.file.url,
32-
'name': orderName(f.name),
33-
"type": "image/png",
34-
'thumbnailUrl': self.object.file.url,
35-
'size': f.size,
36-
'deleteUrl': reverse('upload-delete', args=[self.object.id]),
37-
'deleteType': "DELETE",
38-
}]
13+
files = [serialize(self.object)]
3914
data = {"files": files}
40-
response = JSONResponse(data, {}, response_mimetype(self.request))
15+
response = JSONResponse(data, mimetype=response_mimetype(self.request))
4116
response['Content-Disposition'] = 'inline; filename=files.json'
4217
return response
4318

19+
4420
class BasicVersionCreateView(PictureCreateView):
4521
template_name_suffix = '_basic_form'
4622

23+
4724
class BasicPlusVersionCreateView(PictureCreateView):
4825
template_name_suffix = '_basicplus_form'
4926

27+
5028
class AngularVersionCreateView(PictureCreateView):
5129
template_name_suffix = '_angular_form'
5230

31+
5332
class jQueryVersionCreateView(PictureCreateView):
5433
template_name_suffix = '_jquery_form'
5534

35+
5636
class PictureDeleteView(DeleteView):
5737
model = Picture
5838

5939
def delete(self, request, *args, **kwargs):
6040
self.object = self.get_object()
6141
self.object.delete()
62-
response = JSONResponse(True, {}, response_mimetype(self.request))
42+
response = JSONResponse(True, mimetype=response_mimetype(request))
6343
response['Content-Disposition'] = 'inline; filename=files.json'
6444
return response
6545

66-
def PictureListView(request):
67-
files = []
68-
for obj in Picture.objects.all():
69-
files += [{
70-
'name': orderName(obj.file.name),
71-
'size': obj.file.size,
72-
'url': obj.file.url,
73-
'thumbnailUrl': obj.file.url,
74-
'deleteUrl': reverse('upload-delete', args=[obj.id]),
75-
'deleteType': "DELETE"
76-
}]
77-
data = {"files": files}
78-
response = JSONResponse(data, {}, response_mimetype(request))
79-
response['Content-Disposition'] = 'inline; filename=files.json'
80-
return response
81-
82-
class JSONResponse(HttpResponse):
83-
"""JSON response class."""
84-
def __init__(self,obj='',json_opts={},mimetype="application/json",*args,**kwargs):
85-
content = simplejson.dumps(obj,**json_opts)
86-
super(JSONResponse,self).__init__(content,mimetype,*args,**kwargs)
46+
47+
class PictureListView(View):
48+
def get(self, request, *args, **kwargs):
49+
files = []
50+
for obj in Picture.objects.all():
51+
files.append(serialize(obj))
52+
data = {'files': files}
53+
response = JSONResponse(data, mimetype=response_mimetype(request))
54+
response['Content-Disposition'] = 'inline; filename=files.json'
55+
return response

0 commit comments

Comments
 (0)