示例#1
0
文件: json.py 项目: barryloper/dorthy
def dumps(obj, basename, camel_case=False, ignore_attributes=None, encoding="utf-8"):
    """
    Provides basic json encoding.  Handles encoding of SQLAlchemy objects
    """

    if obj is None:
        return None
    elif isinstance(obj, PRIMITIVE_TYPES):
        return obj
    elif isinstance(obj, bytes):
        return native_str(obj, encoding)
    elif hasattr(obj, "_json"):
        json_obj = getattr(obj, "_json")
        if callable(json_obj):
            return json_obj()
        elif isinstance(json_obj, str):
            return json_obj
        else:
            raise ValueError("Invalid _json attribute found on object")
    elif hasattr(obj, "_as_dict"):
        dict_attr = getattr(obj, "_as_dict")
        if callable(dict_attr):
            return dumps(dict_attr(), basename, camel_case, ignore_attributes, encoding)
        else:
            raise ValueError("Invalid _as_dict attribute found on object")
    elif isinstance(obj, (datetime.date, datetime.datetime)):
        return obj.isoformat()
    elif isinstance(obj, dict) or isinstance(obj, collections.Mapping):
        values = dict()
        for name, value in obj.items():
            name = native_str(name, encoding)
            new_basename = _append_path(basename, name)
            if camel_case:
                name = camel_encode(name)
            if not ignore_attributes or new_basename not in ignore_attributes:
                values[name] = dumps(value, new_basename, camel_case, ignore_attributes, encoding)
        return values
    elif isinstance(obj, collections.Iterable):
        return [dumps(val, basename, camel_case, ignore_attributes, encoding) for val in obj]

    values = dict()
    transients = _get_transients(obj)
    serializable = dir(obj)

    for name in serializable:
        if _is_visible_attribute(obj, name, transients):
            try:
                value = obj.__getattribute__(name)
                new_basename = _append_path(basename, name)
                if _is_visible_type(value) and (not ignore_attributes or new_basename not in ignore_attributes):
                    if camel_case:
                        name = camel_encode(name)
                    values[name] = dumps(value, new_basename, camel_case, ignore_attributes, encoding)
            except Exception:
                continue
    if not values:
        return str(obj)
    else:
        return values
示例#2
0
 def deserialize(self, data):
     dct = json.loads(native_str(data))
     principal = PrincipalJSONSerializer().deserialize(dct["principal"])
     groups = self._deserialize_list(dct.get("groups", None),
                                     GroupJSONSerializer)
     authorities = self._deserialize_list(dct.get("authorities", None),
                                          AuthorityJSONSerializer)
     return SimpleAuthentication(principal, authorities, groups)
示例#3
0
文件: web.py 项目: barryloper/dorthy
 def get_session(self, create=False, timeout=DEFAULT_SESSION_TIMEOUT, update_access=True):
     if self.__session is None:
         session_id = self.__get_session_cookie()
         if session_id:
             self.__session = session_store.load(native_str(session_id))
         if self.__session is None and create:
             self.__session = Session(session_store.generate_session_id(),
                                      timeout=timeout,
                                      update_access=update_access)
             self.__set_session_cookie()
     return self.__session
示例#4
0
文件: core.py 项目: barryloper/dorthy
    def deserialize(self, data):
        """De-serializes a principle

        Args:
            data: the principal represented either as a JSON string
            or a dictionary
        """
        dct = data if isinstance(data, dict) else json.loads(native_str(data))
        uid = dct["uid"]
        name = dct["name"]
        locale = dct.get("locale", None)
        timezone = dct.get("timezone", None)
        return Principal(uid, name, locale, timezone)
示例#5
0
    def deserialize(self, data):
        """De-serializes a principle

        Args:
            data: the principal represented either as a JSON string
            or a dictionary
        """
        dct = data if isinstance(data, dict) else json.loads(native_str(data))
        uid = dct["uid"]
        name = dct["name"]
        locale = dct.get("locale", None)
        timezone = dct.get("timezone", None)
        return Principal(uid, name, locale, timezone)
示例#6
0
 def get_session(self,
                 create=False,
                 timeout=DEFAULT_SESSION_TIMEOUT,
                 update_access=True):
     if self.__session is None:
         session_id = self.__get_session_cookie()
         if session_id:
             self.__session = session_store.load(native_str(session_id))
         if self.__session is None and create:
             self.__session = Session(session_store.generate_session_id(),
                                      timeout=timeout,
                                      update_access=update_access)
             self.__set_session_cookie()
     return self.__session
示例#7
0
文件: core.py 项目: barryloper/dorthy
    def deserialize(self, data):
        """De-serializes a group

        Args:
            data: the group represented either as a JSON string
            or a dictionary
        """
        dct = data if isinstance(data, dict) else json.loads(native_str(data))
        name = dct["name"]
        group_type = dct.get("group_type", None)
        security_group = dct.get("security_group", False)
        primary = dct.get("primary", False)
        effective_date = dct.get("effective_date", None)
        end_date = dct.get("end_date", None)
        attributes = dct.get("attributes", None)
        return Group(name,
                     group_type=group_type,
                     security_group=security_group,
                     primary=primary,
                     effective_date=effective_date,
                     end_date=end_date,
                     attributes=attributes)
示例#8
0
    def deserialize(self, data):
        """De-serializes a group

        Args:
            data: the group represented either as a JSON string
            or a dictionary
        """
        dct = data if isinstance(data, dict) else json.loads(native_str(data))
        name = dct["name"]
        group_type = dct.get("group_type", None)
        security_group = dct.get("security_group", False)
        primary = dct.get("primary", False)
        effective_date = dct.get("effective_date", None)
        end_date = dct.get("end_date", None)
        attributes = dct.get("attributes", None)
        return Group(name,
                     group_type=group_type,
                     security_group=security_group,
                     primary=primary,
                     effective_date=effective_date,
                     end_date=end_date,
                     attributes=attributes)
示例#9
0
def dumps(obj,
          basename,
          camel_case=False,
          ignore_attributes=None,
          encoding="utf-8"):
    """
    Provides basic json encoding.  Handles encoding of SQLAlchemy objects
    """

    if obj is None:
        return None
    elif isinstance(obj, PRIMITIVE_TYPES):
        return obj
    elif isinstance(obj, bytes):
        return native_str(obj, encoding)
    elif hasattr(obj, "_json"):
        json_obj = getattr(obj, "_json")
        if callable(json_obj):
            return json_obj()
        elif isinstance(json_obj, str):
            return json_obj
        else:
            raise ValueError("Invalid _json attribute found on object")
    elif hasattr(obj, "_as_dict"):
        dict_attr = getattr(obj, "_as_dict")
        if callable(dict_attr):
            return dumps(dict_attr(), basename, camel_case, ignore_attributes,
                         encoding)
        else:
            raise ValueError("Invalid _as_dict attribute found on object")
    elif isinstance(obj, (datetime.date, datetime.datetime)):
        return obj.isoformat()
    elif isinstance(obj, dict) or isinstance(obj, collections.Mapping):
        values = dict()
        for name, value in obj.items():
            name = native_str(name, encoding)
            new_basename = _append_path(basename, name)
            if camel_case:
                name = camel_encode(name)
            if not ignore_attributes or new_basename not in ignore_attributes:
                values[name] = dumps(value, new_basename, camel_case,
                                     ignore_attributes, encoding)
        return values
    elif isinstance(obj, collections.Iterable):
        return [
            dumps(val, basename, camel_case, ignore_attributes, encoding)
            for val in obj
        ]

    values = dict()
    transients = _get_transients(obj)
    serializable = dir(obj)

    for name in serializable:
        if _is_visible_attribute(obj, name, transients):
            try:
                value = obj.__getattribute__(name)
                new_basename = _append_path(basename, name)
                if _is_visible_type(value) and (not ignore_attributes
                                                or new_basename
                                                not in ignore_attributes):
                    if camel_case:
                        name = camel_encode(name)
                    values[name] = dumps(value, new_basename, camel_case,
                                         ignore_attributes, encoding)
            except Exception:
                continue
    if not values:
        return str(obj)
    else:
        return values
示例#10
0
def _append_path(basename, name):
    if basename:
        return native_str(basename + '.' + name)
    else:
        return native_str(name)
示例#11
0
文件: core.py 项目: barryloper/dorthy
 def deserialize(self, data):
     dct = json.loads(native_str(data))
     principal = PrincipalJSONSerializer().deserialize(dct["principal"])
     groups = self._deserialize_list(dct.get("groups", None), GroupJSONSerializer)
     authorities = self._deserialize_list(dct.get("authorities", None), AuthorityJSONSerializer)
     return SimpleAuthentication(principal, authorities, groups)
示例#12
0
 def deserialize(self, data):
     dct = data if isinstance(data, dict) else json.loads(native_str(data))
     authority = dct["authority"]
     permission = dct.get("permission", None)
     return Authority(authority, permission)
示例#13
0
 def deserialize(self, data):
     dct = data if isinstance(data, dict) else json.loads(native_str(data))
     authority = dct["authority"]
     permission = dct.get("permission", None)
     return Authority(authority, permission)
示例#14
0
def create_key(prefix, key, decode_key=False):
    key = key if not decode_key else native_str(key)
    return "{}:{}".format(prefix, key)
示例#15
0
文件: json.py 项目: barryloper/dorthy
def _append_path(basename, name):
    if basename:
        return native_str(basename + "." + name)
    else:
        return native_str(name)