File: serialization.rst

package info (click to toggle)
django-tastypie 0.9.10-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 1,020 kB
  • sloc: python: 6,530; makefile: 78; sh: 45
file content (293 lines) | stat: -rw-r--r-- 7,901 bytes parent folder | download
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
.. _ref-serialization:

=============
Serialization
=============

Serialization can be one of the most contentious areas of an API. Everyone
has their own requirements, their own preferred output format & the desire to
have control over what is returned.

As a result, Tastypie ships with a serializer that tries to meet the basic
needs of most use cases, and the flexibility to go outside of that when you
need to.

The default ``Serializer`` supports the following formats:

* json
* jsonp
* xml
* yaml
* html

Usage
=====

Using this class is simple. It is the default option on all ``Resource``
classes unless otherwise specified. The following code is a no-op, but
demonstrate how you could use your own serializer::

    from django.contrib.auth.models import User
    from tastypie.resources import ModelResource
    from tastypie.serializers import Serializer
    
    
    class UserResource(ModelResource):
        class Meta:
            queryset = User.objects.all()
            resource_name = 'auth/user'
            excludes = ['email', 'password', 'is_superuser']
            # Add it here.
            serializer = Serializer()


Implementing Your Own Serializer
================================

There are several different use cases here. We'll cover simple examples of
wanting a tweaked format & adding a different format.

To tweak a format, simply override it's ``to_<format>`` & ``from_<format>``
methods. So adding the server time to all output might look like so::

    import time
    from tastypie.serializers import Serializer
    
    
    class CustomJSONSerializer(Serializer):
        def to_json(self, data, options=None):
            options = options or {}
            
            data = self.to_simple(data, options)

            # Add in the current time.
            data['requested_time'] = time.time()

            return simplejson.dumps(data, cls=json.DjangoJSONEncoder, sort_keys=True)
        
        def from_json(self, content):
            data = simplejson.loads(content)
            
            if 'requested_time' in data:
                # Log the request here...
                pass
            
            return data

In the case of adding a different format, let's say you want to add a CSV
output option to the existing set. Your ``Serializer`` subclass might look
like::

    import csv
    import StringIO
    from tastypie.serializers import Serializer
    
    
    class CSVSerializer(Serializer):
        formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'csv']
        content_types = {
            'json': 'application/json',
            'jsonp': 'text/javascript',
            'xml': 'application/xml',
            'yaml': 'text/yaml',
            'html': 'text/html',
            'csv': 'text/csv',
        }
        
        def to_csv(self, data, options=None):
            options = options or {}
            data = self.to_simple(data, options)
            raw_data = StringIO.StringIO()
            # Untested, so this might not work exactly right.
            for item in data:
                writer = csv.DictWriter(raw_data, item.keys(), extrasaction='ignore')
                writer.write(item)
            return raw_data
        
        def from_csv(self, content):
            raw_data = StringIO.StringIO(content)
            data = []
            # Untested, so this might not work exactly right.
            for item in csv.DictReader(raw_data):
                data.append(item)
            return data

``Serializer`` Methods
======================

A swappable class for serialization.

This handles most types of data as well as the following output formats::

    * json
    * jsonp
    * xml
    * yaml
    * html

It was designed to make changing behavior easy, either by overridding the
various format methods (i.e. ``to_json``), by changing the
``formats/content_types`` options or by altering the other hook methods.

``get_mime_for_format``
~~~~~~~~~~~~~~~~~~~~~~~

.. method:: Serializer.get_mime_for_format(self, format):

Given a format, attempts to determine the correct MIME type.

If not available on the current ``Serializer``, returns
``application/json`` by default.

``format_datetime``
~~~~~~~~~~~~~~~~~~~

.. method:: Serializer.format_datetime(data):

A hook to control how datetimes are formatted.

Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).

Default is ``iso-8601``, which looks like "2010-12-16T03:02:14".

``format_date``
~~~~~~~~~~~~~~~

.. method:: Serializer.format_date(data):

A hook to control how dates are formatted.

Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).

Default is ``iso-8601``, which looks like "2010-12-16".

``format_time``
~~~~~~~~~~~~~~~

.. method:: Serializer.format_time(data):

A hook to control how times are formatted.

Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).

Default is ``iso-8601``, which looks like "03:02:14".

``serialize``
~~~~~~~~~~~~~

.. method:: Serializer.serialize(self, bundle, format='application/json', options={}):

Given some data and a format, calls the correct method to serialize
the data and returns the result.

``deserialize``
~~~~~~~~~~~~~~~

.. method:: Serializer.deserialize(self, content, format='application/json'):

Given some data and a format, calls the correct method to deserialize
the data and returns the result.

``to_simple``
~~~~~~~~~~~~~

.. method:: Serializer.to_simple(self, data, options):

For a piece of data, attempts to recognize it and provide a simplified
form of something complex.

This brings complex Python data structures down to native types of the
serialization format(s).

``to_etree``
~~~~~~~~~~~~

.. method:: Serializer.to_etree(self, data, options=None, name=None, depth=0):

Given some data, converts that data to an ``etree.Element`` suitable
for use in the XML output.

``from_etree``
~~~~~~~~~~~~~~

.. method:: Serializer.from_etree(self, data):

Not the smartest deserializer on the planet. At the request level,
it first tries to output the deserialized subelement called "object"
or "objects" and falls back to deserializing based on hinted types in
the XML element attribute "type".

``to_json``
~~~~~~~~~~~

.. method:: Serializer.to_json(self, data, options=None):

Given some Python data, produces JSON output.

``from_json``
~~~~~~~~~~~~~

.. method:: Serializer.from_json(self, content):

Given some JSON data, returns a Python dictionary of the decoded data.

``to_jsonp``
~~~~~~~~~~~~

.. method:: Serializer.to_jsonp(self, data, options=None):

Given some Python data, produces JSON output wrapped in the provided
callback.

``to_xml``
~~~~~~~~~~

.. method:: Serializer.to_xml(self, data, options=None):

Given some Python data, produces XML output.

``from_xml``
~~~~~~~~~~~~

.. method:: Serializer.from_xml(self, content):

Given some XML data, returns a Python dictionary of the decoded data.

``to_yaml``
~~~~~~~~~~~

.. method:: Serializer.to_yaml(self, data, options=None):

Given some Python data, produces YAML output.

``from_yaml``
~~~~~~~~~~~~~

.. method:: Serializer.from_yaml(self, content):

Given some YAML data, returns a Python dictionary of the decoded data.

``to_html``
~~~~~~~~~~~

.. method:: Serializer.to_html(self, data, options=None):

Reserved for future usage.

The desire is to provide HTML output of a resource, making an API
available to a browser. This is on the TODO list but not currently
implemented.

``from_html``
~~~~~~~~~~~~~

.. method:: Serializer.from_html(self, content):

Reserved for future usage.

The desire is to handle form-based (maybe Javascript?) input, making an
API available to a browser. This is on the TODO list but not currently
implemented.