Skip to content

Commit ce66fc1

Browse files
committed
Merge pull request sigurdga#39 from ET-CS/master
João Paulo changes
2 parents 2ec7f80 + 206991a commit ce66fc1

File tree

5 files changed

+109
-62
lines changed

5 files changed

+109
-62
lines changed

fileupload/models.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1+
# encoding: utf-8
12
from django.db import models
23

3-
class Picture(models.Model):
44

5-
# This is a small demo using just two fields. The slug field is really not
6-
# necessary, but makes the code simpler. ImageField depends on PIL or
7-
# pillow (where Pillow is easily installable in a virtualenv. If you have
8-
# problems installing pillow, use a more generic FileField instead.
5+
class Picture(models.Model):
6+
"""This is a small demo using just two fields. The slug field is really not
7+
necessary, but makes the code simpler. ImageField depends on PIL or
8+
pillow (where Pillow is easily installable in a virtualenv. If you have
9+
problems installing pillow, use a more generic FileField instead.
910
10-
#file = models.FileField(upload_to="pictures")
11+
"""
1112
file = models.ImageField(upload_to="pictures")
1213
slug = models.SlugField(max_length=50, blank=True)
1314

@@ -22,7 +23,7 @@ def save(self, *args, **kwargs):
2223
self.slug = self.file.name
2324
super(Picture, self).save(*args, **kwargs)
2425

25-
# remove to leave file.
2626
def delete(self, *args, **kwargs):
27+
"""delete -- Remove to leave file."""
2728
self.file.delete(False)
2829
super(Picture, self).delete(*args, **kwargs)

fileupload/response.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
"""JSONResponse -- Extends HTTPResponse to handle JSON format response.
24+
25+
This response can be used in any view that should return a json stream of
26+
data.
27+
28+
Usage:
29+
30+
def a_iew(request):
31+
content = {'key': 'value'}
32+
return JSONResponse(content, mimetype=response_mimetype(request))
33+
34+
"""
35+
def __init__(self, obj='', json_opts=None, mimetype=MIMEJSON, *args, **kwargs):
36+
json_opts = json_opts if isinstance(json_opts, dict) else {}
37+
content = simplejson.dumps(obj, **json_opts)
38+
super(JSONResponse, self).__init__(content, mimetype, *args, **kwargs)

fileupload/serialize.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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 a text to 20 chars length, if necessary strips the
9+
middle of the text and substitute it for an ellipsis.
10+
11+
name -- text to be limited.
12+
13+
"""
14+
name = re.sub(r'^.*/', '', name)
15+
if len(name) <= 20:
16+
return name
17+
return name[:10] + "..." + name[-7:]
18+
19+
20+
def serialize(instance, file_attr='file'):
21+
"""serialize -- Serialize a Picture instance into a dict.
22+
23+
instance -- Picture instance
24+
file_attr -- attribute name that contains the FileField or ImageField
25+
26+
"""
27+
obj = getattr(instance, file_attr)
28+
return {
29+
'url': obj.url,
30+
'name': order_name(obj.name),
31+
'type': mimetypes.guess_type(obj.path)[0] or 'image/png',
32+
'thumbnailUrl': obj.url,
33+
'size': obj.size,
34+
'deleteUrl': reverse('upload-delete', args=[instance.pk]),
35+
'deleteType': 'DELETE',
36+
}
37+
38+

fileupload/urls.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# encoding: utf-8
12
from django.conf.urls import patterns, url
23
from fileupload.views import BasicVersionCreateView, BasicPlusVersionCreateView, PictureCreateView, AngularVersionCreateView, jQueryVersionCreateView, PictureDeleteView
34

fileupload/views.py

+24-55
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-
}]
39-
data = {"files": files}
40-
response = JSONResponse(data, {}, response_mimetype(self.request))
13+
files = [serialize(self.object)]
14+
data = {'files': files}
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)