~widelands-dev/widelands-website/trunk

« back to all changes in this revision

Viewing changes to threadedcomments/utils.py

  • Committer: Holger Rapp
  • Date: 2019-06-21 18:34:42 UTC
  • mfrom: (540.1.3 update_ops_script)
  • Revision ID: sirver@gmx.de-20190621183442-y2ulybzr0rdvfefd
Adapt the update script for the new server.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from django.core.serializers import serialize
 
2
from django.http import HttpResponse
 
3
from django.utils.functional import Promise
 
4
from django.utils.encoding import force_text
 
5
import json as simplejson
 
6
 
 
7
 
 
8
class LazyEncoder(simplejson.JSONEncoder):
 
9
 
 
10
    def default(self, obj):
 
11
        if isinstance(obj, Promise):
 
12
            return force_text(obj)
 
13
        return obj
 
14
 
 
15
 
 
16
class JSONResponse(HttpResponse):
 
17
    """A simple subclass of ``HttpResponse`` which makes serializing to JSON
 
18
    easy."""
 
19
 
 
20
    def __init__(self, object, is_iterable=True):
 
21
        if is_iterable:
 
22
            content = serialize('json', object)
 
23
        else:
 
24
            content = simplejson.dumps(object, cls=LazyEncoder)
 
25
        super(JSONResponse, self).__init__(
 
26
            content, mimetype='application/json')
 
27
 
 
28
 
 
29
class XMLResponse(HttpResponse):
 
30
    """A simple subclass of ``HttpResponse`` which makes serializing to XML
 
31
    easy."""
 
32
 
 
33
    def __init__(self, object, is_iterable=True):
 
34
        if is_iterable:
 
35
            content = serialize('xml', object)
 
36
        else:
 
37
            content = object
 
38
        super(XMLResponse, self).__init__(content, mimetype='application/xml')