Debian Codegraph @

neutronclient/common/serializer.py

raw
1 # Copyright 2013 OpenStack Foundation.
2 # All Rights Reserved
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 from oslo_serialization import jsonutils
17
18 from neutronclient._i18n import _
19 from neutronclient.common import exceptions as exception
20
21
22 class ActionDispatcher(object):
23 """Maps method name to local methods through action name."""
24
25 def dispatch(self, *args, **kwargs):
26 """Find and call local method."""
27 action = kwargs.pop('action', 'default')
28 action_method = getattr(self, str(action), self.default)
29 return action_method(*args, **kwargs)
30
31 def default(self, data):
32 raise NotImplementedError()
33
34
35 class DictSerializer(ActionDispatcher):
36 """Default request body serialization."""
37
38 def serialize(self, data, action='default'):
39 return self.dispatch(data, action=action)
40
41 def default(self, data):
42 return ""
43
44
45 class JSONDictSerializer(DictSerializer):
46 """Default JSON request body serialization."""
47
48 def default(self, data):
49 def sanitizer(obj):
50 return str(obj)
51 return jsonutils.dumps(data, default=sanitizer)
52
53
54 class TextDeserializer(ActionDispatcher):
55 """Default request body deserialization."""
56
57 def deserialize(self, datastring, action='default'):
58 return self.dispatch(datastring, action=action)
59
60 def default(self, datastring):
61 return {}
62
63
64 class JSONDeserializer(TextDeserializer):
65
66 def _from_json(self, datastring):
67 try:
68 return jsonutils.loads(datastring)
69 except ValueError:
70 msg = _("Cannot understand JSON")
71 raise exception.MalformedResponseBody(reason=msg)
72
73 def default(self, datastring):
74 return {'body': self._from_json(datastring)}
75
76
77 # NOTE(maru): this class is duplicated from neutron.wsgi
78 class Serializer(object):
79 """Serializes and deserializes dictionaries to certain MIME types."""
80
81 def __init__(self, metadata=None):
82 """Create a serializer based on the given WSGI environment.
83
84 'metadata' is an optional dict mapping MIME types to information
85 needed to serialize a dictionary to that type.
86
87 """
88 self.metadata = metadata or {}
89
90 def _get_serialize_handler(self, content_type):
91 handlers = {
92 'application/json': JSONDictSerializer(),
93 }
94
95 try:
96 return handlers[content_type]
97 except Exception:
98 raise exception.InvalidContentType(content_type=content_type)
99
100 def serialize(self, data):
101 """Serialize a dictionary into the specified content type."""
102 return self._get_serialize_handler("application/json").serialize(data)
103
104 def deserialize(self, datastring):
105 """Deserialize a string to a dictionary.
106
107 The string must be in the format of a supported MIME type.
108 """
109 return self.get_deserialize_handler("application/json").deserialize(
110 datastring)
111
112 def get_deserialize_handler(self, content_type):
113 handlers = {
114 'application/json': JSONDeserializer(),
115 }
116
117 try:
118 return handlers[content_type]
119 except Exception:
120 raise exception.InvalidContentType(content_type=content_type)