yakumo.mapper

Package yakumo :: Module mapper |
[hide private]
[frames] | no frames]

# Source Code for Module yakumo.mapper

      1  # Copyright 2014-2017 by Akira Yoshiyama <akirayoshiyama@gmail.com>.
      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  """
     17  Mapper classes
     18  """
     19
     20  import base64
     21  import json
     22  from datetime import datetime
     23  import dateutil.parser
     24
     25
     26 -def make_mappings(source, to_json, to_attr):
     27      for attr, json_attr, _mapper in source:
     28          if isinstance(attr, str):
     29              if attr not in to_json:
     30                  to_json[attr] = {
     31                      'json_attr': json_attr,
     32                      'mapper': _mapper,
     33                  }
     34          if isinstance(json_attr, str):
     35              to_attr[json_attr] = {
     36                  'attr': attr,
     37                  'mapper': _mapper,
     38              }
     39
     40
     41 -class NoopClass(object):
     42
     43      @staticmethod
     44 -    def to_attr(manager_class, attr, do_raise=False):
     45          return attr
     46
     47      @staticmethod
     48 -    def to_json(manager_class, attr):
     49          return attr
     50
     51
     52 -class IntStrClass(object):
     53
     54      @staticmethod
     55 -    def to_attr(manager_class, attr, do_raise=False):
     56          return int(attr)
     57
     58      @staticmethod
     59 -    def to_json(manager_class, attr):
     60          return str(attr)
     61
     62
     63 -class StrIntClass(object):
     64
     65      @staticmethod
     66 -    def to_attr(manager_class, attr, do_raise=False):
     67          return str(attr)
     68
     69      @staticmethod
     70 -    def to_json(manager_class, attr):
     71          return int(attr)
     72
     73
     74 -class FloatStrClass(object):
     75
     76      @staticmethod
     77 -    def to_attr(manager_class, attr, do_raise=False):
     78          return float(attr)
     79
     80      @staticmethod
     81 -    def to_json(manager_class, attr):
     82          return str(attr)
     83
     84
     85 -class BoolStrClass(object):
     86
     87      @staticmethod
     88 -    def to_attr(manager_class, attr, do_raise=False):
     89          if attr.lower() == 'true':
     90              return True
     91          if attr.lower() == 'false':
     92              return False
     93          return None
     94
     95      @staticmethod
     96 -    def to_json(manager_class, attr):
     97          if attr is True:
     98              return 'true'
     99          if attr is False:
    100              return 'false'
    101          return None
    102
    103
    104 -class JSONClass(object):
    105
    106      @staticmethod
    107 -    def to_attr(manager_class, attr, do_raise=False):
    108          return json.loads(attr)
    109
    110      @staticmethod
    111 -    def to_json(manager_class, attr):
    112          return json.dumps(attr)
    113
    114
    115 -class Base64(object):
    116
    117      @staticmethod
    118 -    def to_attr(manager_class, attr, do_raise=False):
    119          return base64.b64decode(attr)
    120
    121      @staticmethod
    122 -    def to_json(manager_class, attr):
    123          return base64.b64encode(attr)
    124
    125
    126 -class DateTimeClass(object):
    127
    128      @staticmethod
    129 -    def to_attr(manager_class, attr, do_raise=False):
    130          try:
    131              return dateutil.parser.parse(attr)
    132          except:
    133              return None
    134
    135      @staticmethod
    136 -    def to_json(manager_class, attr):
    137          try:
    138              return datetime.isoformat(attr)
    139          except:
    140              return None
    141
    142
    143 -class Simple(object):
    144
    145 -    def __init__(self, mapping):
    146          self.mapping = mapping
    147
    148 -    def to_attr(self, manager_class, value, do_raise=False):
    149          for obj_value, json_value in self.mapping:
    150              if json_value == value:
    151                  return obj_value
    152
    153 -    def to_json(self, manager_class, value):
    154          for obj_value, json_value in self.mapping:
    155              if obj_value == value:
    156                  return json_value
    157
    158
    159 -class Resource(object):
    160
    161      manager_class = None
    162
    163 -    def __init__(self, manager_path):
    164          self.manager_path = manager_path
    165
    166 -    def _load_manager_class(self, manager_class):
    167          if self.manager_class:
    168              return
    169          resource = manager_class._client
    170          for path in self.manager_path.split('.'):
    171              resource = getattr(resource, path)
    172          self.manager_class = resource
    173
    174 -    def to_attr(self, manager_class, id, do_raise=False):
    175          if id is None:
    176              return None
    177          self._load_manager_class(manager_class)
    178          return self.manager_class.get_empty(id)
    179
    180 -    def to_json(self, manager_class, obj):
    181          if obj is None:
    182              return None
    183          self._load_manager_class(manager_class)
    184          return obj._id
    185
    186
    187 -class List(object):
    188
    189      mapper = None
    190
    191 -    def __init__(self, mapper):
    192          self.mapper = mapper
    193
    194 -    def to_attr(self, manager_class, attr, do_raise=False):
    195          return [self.mapper.to_attr(manager_class, x) for x in attr]
    196
    197 -    def to_json(self, manager_class, attr):
    198          return [self.mapper.to_json(manager_class, x) for x in attr]
    199
    200
    201 -class Dict(object):
    202
    203      mappers = None
    204
    205 -    def __init__(self, mappers):
    206          # mappers has list like below
    207          # [('subnet', 'subnet_ip', mapper.Resource('subnet')),
    208          #  ('ip_address', 'ip_address', mapper.Noop)}]
    209          self.mappers = mappers
    210
    211 -    def to_attr(self, manager_class, attr, do_raise=False):
    212          if attr is None:
    213              return {}
    214          ret = {}
    215          for _attr, _json, mapper in self.mappers:
    216              if _json in attr:
    217                  ret[_attr] = mapper.to_attr(manager_class, attr[_json])
    218          return ret
    219
    220 -    def to_json(self, manager_class, attr):
    221          if attr is None:
    222              return {}
    223          converted = []
    224          ret = {}
    225          for _attr, _json, mapper in self.mappers:
    226              if _attr in attr and _attr not in converted:
    227                  converted.append(_attr)
    228                  ret[_json] = mapper.to_json(manager_class, attr[_attr])
    229          return ret
    230
    231
    232  Noop = NoopClass()
    233  IntStr = IntStrClass()
    234  StrInt = StrIntClass()
    235  FloatStr = FloatStrClass()
    236  BoolStr = BoolStrClass()
    237  JSON = JSONClass()
    238  DateTime = DateTimeClass()
    239