示例#1
0
    def readjsonstructure(self,
                          project_id,
                          visibility_filter=StaticFiltersFactory.FULL_VIEW,
                          first_level=None,
                          second_level=None,
                          filter_value=None):
        """
        AJAX exposed method. 
        Will return the complete JSON for Project's structure, or filtered tree
        (filter only Relevant entities or Burst only Data).
        """
        if first_level is None or second_level is None:
            first_level, second_level = self.get_project_structure_grouping()
        else:
            self.set_project_structure_grouping(first_level, second_level)

        selected_filter = StaticFiltersFactory.build_datatype_filters(
            single_filter=visibility_filter)
        if project_id == 'undefined':
            project_id = common.get_current_project().id
        project = self.project_service.find_project(project_id)
        json_structure = self.project_service.get_project_structure(
            project, selected_filter, first_level, second_level, filter_value)
        # This JSON encoding is necessary, otherwise we will get an error
        # from JSTree library while trying to load with AJAX
        # the content of the tree.
        encoder = JSONEncoder()
        return encoder.iterencode(json_structure)
示例#2
0
文件: members.py 项目: zagy/karl
def member_search_json_view(context, request):
    try:
        # Query parameter shall be 'term'.
        prefix = request.params['term']
    except UnicodeDecodeError:
        # not utf8, just return empty list since tags can't have these chars
        result = JSONEncoder().encode([])
        return Response(result, content_type="application/x-json")
    # case insensitive
    prefix = prefix.lower()
    community = find_interface(context, ICommunity)
    member_names = community.member_names
    moderator_names = community.moderator_names
    community_member_names = member_names.union(moderator_names)
    query = dict(
        member_name='%s*' % prefix,
        sort_index='title',
        limit=20,
    )
    searcher = ICatalogSearch(context)
    try:
        total, docids, resolver = searcher(**query)
        profiles = filter(None, map(resolver, docids))
        records = [
            dict(
                value=profile.__name__,
                label=profile.title,
            ) for profile in profiles
            if profile.__name__ not in community_member_names
            and profile.security_state != 'inactive'
        ]
    except ParseError:
        records = []
    result = JSONEncoder().encode(records)
    return Response(result, content_type="application/x-json")
示例#3
0
    def __init__(self, *args, **kwargs):
        JSONEncoder.__init__(self)

        if args and kwargs:
            raise ValueError("Please provide either args or kwargs, not both.")

        self.__args = args
        self.__kwargs = kwargs
示例#4
0
  def __init__( self, *args, **kwargs ):
    JSONEncoder.__init__( self )

    if args and kwargs:
      raise ValueError( "Please provide either args or kwargs, not both." )

    self.__args = args
    self.__kwargs = kwargs
示例#5
0
 def test_get_project_structure(self):
     dt_factory = datatypes_factory.DatatypesFactory()
     self._create_datatypes(dt_factory, 3)
     node_json = self.project_service.get_project_structure(
         dt_factory.project, None, 'Data_State', 'Data_Subject', None)
     encoder = JSONEncoder()
     encoder.iterencode(node_json)
     # No exceptions were raised so far.
     project_dts = dao.get_datatypes_for_project(dt_factory.project.id)
     for dt in project_dts:
         self.assertTrue(
             dt.gid in node_json,
             "Should have all datatypes present in resulting json.")
示例#6
0
文件: tags.py 项目: zagy/karl
def jquery_tag_search_view(context, request):
    tag_query_tool = getMultiAdapter((context, request), ITagQuery)
    try:
        prefix = request.params['val']
    except UnicodeDecodeError:
        # not utf8, just return empty list since tags can't have these chars
        result = JSONEncoder().encode([])
        return Response(result, content_type="application/x-json")
    # case insensitive
    prefix = prefix.lower()
    values = tag_query_tool.tags_with_prefix(prefix)
    records = [dict(text=value) for value in values]
    result = JSONEncoder().encode(records)
    return Response(result, content_type="application/x-json")
示例#7
0
文件: jsonify.py 项目: st2sandbox/st2
 def default(self, obj):  # pylint: disable=method-hidden
     if hasattr(obj, "__json__") and six.callable(obj.__json__):
         return obj.__json__()
     elif isinstance(obj, bson.ObjectId):
         return str(obj)
     else:
         return JSONEncoder.default(self, obj)
def convert_MediaElchNFO_to_JSON(filename):
    tree = etree.parse(filename)
    root = tree.getroot()
    #dumpLeaf(root)
    movie = {}
    encodeLeaf(root, movie)
    return JSONEncoder().encode(movie)
示例#9
0
def redis_cluster_fosc_add(fid,
                           isp,
                           peer_id,
                           version,
                           nat_type,
                           public_ip,
                           public_port,
                           private_ip,
                           private_port,
                           stun_ip,
                           cppc=1,
                           ppc=304):
    """
    在FOSC中set value,若非必要,尽量使用cache_report或control_report请求汇报,由ts-go服务器写入FOSC
    目前服务器维护seed list不只单单使用FOSC,还涉及到LFC,LFCacheManageZset
    """
    key = "{FOSC_" + str(fid) + "_" + str(isp) + "}"
    value = {
        "peer_id": str(peer_id),
        "version": str(version),
        "natType": int(nat_type),
        "publicIP": str(public_ip),
        "publicPort": int(public_port),
        "privateIP": str(private_ip),
        "privatePort": int(private_port),
        "stunIP": str(stun_ip),
        "cppc": int(cppc),
        "ppc": int(ppc)
    }
    # 将dict转成json格式
    value = JSONEncoder().encode(value)
    rc.sadd(key, value)
示例#10
0
    def default(self, obj):
        '''
        Converts an object and returns a ``JSON``-friendly structure.

        :param obj: object or structure to be converted into a
                    ``JSON``-ifiable structure

        Considers the following special cases in order:

        * object has a callable __json__() attribute defined
            returns the result of the call to __json__()
        * date and datetime objects
            returns the object cast to str
        * Decimal objects
            returns the object cast to float
        * SQLAlchemy objects
            returns a copy of the object.__dict__ with internal SQLAlchemy
            parameters removed
        * SQLAlchemy ResultProxy objects
            Casts the iterable ResultProxy into a list of tuples containing
            the entire resultset data, returns the list in a dictionary
            along with the resultset "row" count.

            .. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',),
                ('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]}

        * SQLAlchemy RowProxy objects
            Casts the RowProxy cursor object into a dictionary, probably
            losing its ordered dictionary behavior in the process but
            making it JSON-friendly.
        * webob_dicts objects
            returns webob_dicts.mixed() dictionary, which is guaranteed
            to be JSON-friendly.
        '''
        if hasattr(obj, '__json__') and six.callable(obj.__json__):
            return obj.__json__()
        elif isinstance(obj, (date, datetime)):
            return str(obj)
        elif isinstance(obj, Decimal):
            # XXX What to do about JSONEncoder crappy handling of Decimals?
            # SimpleJSON has better Decimal encoding than the std lib
            # but only in recent versions
            return float(obj)
        elif is_saobject(obj):
            props = {}
            for key in obj.__dict__:
                if not key.startswith('_sa_'):
                    props[key] = getattr(obj, key)
            return props
        elif isinstance(obj, ResultProxy):
            props = dict(rows=list(obj), count=obj.rowcount)
            if props['count'] < 0:
                props['count'] = len(props['rows'])
            return props
        elif isinstance(obj, RowProxy):
            return dict(obj)
        elif isinstance(obj, webob_dicts):
            return obj.mixed()
        else:
            return JSONEncoder.default(self, obj)
示例#11
0
文件: json.py 项目: dominicgs/Website
    def iterencode(self, obj):
        def _iterconvert(obj):
            # namedtuple/sqlalchemy result
            if isinstance(obj, tuple) and hasattr(obj, '_asdict'):
                # this doesn't include any columns without label()s
                dct = obj._asdict()
                # sqlalchemy result's asdict has broken ordering
                if not isinstance(dct, OrderedDict):
                    dct = OrderedDict((k, dct[k]) for k in obj._fields)
                obj = dct

            if isinstance(obj, db.Model.query_class):
                return [_iterconvert(o) for o in obj]
            elif isinstance(obj, db.Model):
                return to_dict(obj)
            elif isinstance(obj, (list, tuple)):
                return [_iterconvert(o) for o in obj]
            elif isinstance(obj, dict):
                items = obj.items()
                if not isinstance(obj, OrderedDict):
                    # same as sort_keys=True
                    items = sorted(items, key=lambda kv: kv[0])
                return OrderedDict([(k, _iterconvert(v)) for k, v in items])

            return obj

        return JSONEncoder.iterencode(self, _iterconvert(obj))
示例#12
0
文件: members.py 项目: zagy/karl
def jquery_member_search_view(context, request):
    prefix = request.params['val'].lower()
    community = find_interface(context, ICommunity)
    member_names = community.member_names
    moderator_names = community.moderator_names
    community_member_names = member_names.union(moderator_names)
    query = dict(
        member_name='%s*' % prefix,
        sort_index='title',
        limit=20,
    )
    searcher = ICatalogSearch(context)
    try:
        total, docids, resolver = searcher(**query)
        profiles = filter(None, map(resolver, docids))
        records = [
            dict(
                id=profile.__name__,
                text=profile.title,
            ) for profile in profiles
            if profile.__name__ not in community_member_names
            and profile.security_state != 'inactive'
        ]
    except ParseError:
        records = []
    result = JSONEncoder().encode(records)
    return Response(result, content_type="application/x-json")
示例#13
0
def set_allow_weight(isp, pro, lp_ip_list):
    rc = redis.StrictRedis(host=REDIS_SINGLE_HOST, port=REDIS_PORT, db=0)
    key = "ALLOW_WEIGHT-" + str(isp) + "_" + str(pro)
    value = lp_ip_list
    # 将dict转成json格式
    value = JSONEncoder().encode(value)
    rc.set(key, value)
示例#14
0
    def iterencode(self, obj):
        def _iterconvert(obj):
            # namedtuple/sqlalchemy result
            if isinstance(obj, tuple) and hasattr(obj, "_asdict"):
                # this doesn't include any columns without label()s
                dct = obj._asdict()
                # sqlalchemy result's asdict has broken ordering
                if not isinstance(dct, OrderedDict):
                    dct = OrderedDict((k, dct[k]) for k in obj._fields)
                obj = dct

            if isinstance(obj, db.Model.query_class):
                return [_iterconvert(o) for o in obj]
            elif isinstance(obj, db.Model):
                return to_dict(obj)
            elif isinstance(obj, (list, tuple)):
                return [_iterconvert(o) for o in obj]
            elif isinstance(obj, dict):
                items = obj.items()
                if not isinstance(obj, OrderedDict):
                    # same as sort_keys=True
                    items = sorted(items, key=lambda kv: kv[0])
                return OrderedDict([(k, _iterconvert(v)) for k, v in items])

            return obj

        return JSONEncoder.iterencode(self, _iterconvert(obj))
示例#15
0
    def default(self, obj):
        '''
        Converts an object and returns a ``JSON``-friendly structure.

        :param obj: object or structure to be converted into a
                    ``JSON``-ifiable structure

        Considers the following special cases in order:

        * object has a callable __json__() attribute defined
            returns the result of the call to __json__()
        * date and datetime objects
            returns the object cast to str
        * Decimal objects
            returns the object cast to float
        * SQLAlchemy objects
            returns a copy of the object.__dict__ with internal SQLAlchemy
            parameters removed
        * SQLAlchemy ResultProxy objects
            Casts the iterable ResultProxy into a list of tuples containing
            the entire resultset data, returns the list in a dictionary
            along with the resultset "row" count.

            .. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',),
                ('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]}

        * SQLAlchemy RowProxy objects
            Casts the RowProxy cursor object into a dictionary, probably
            losing its ordered dictionary behavior in the process but
            making it JSON-friendly.
        * webob_dicts objects
            returns webob_dicts.mixed() dictionary, which is guaranteed
            to be JSON-friendly.
        '''
        if hasattr(obj, '__json__') and six.callable(obj.__json__):
            return obj.__json__()
        elif isinstance(obj, (date, datetime)):
            return str(obj)
        elif isinstance(obj, Decimal):
            # XXX What to do about JSONEncoder crappy handling of Decimals?
            # SimpleJSON has better Decimal encoding than the std lib
            # but only in recent versions
            return float(obj)
        elif is_saobject(obj):
            props = {}
            for key in obj.__dict__:
                if not key.startswith('_sa_'):
                    props[key] = getattr(obj, key)
            return props
        elif isinstance(obj, ResultProxy):
            props = dict(rows=list(obj), count=obj.rowcount)
            if props['count'] < 0:
                props['count'] = len(props['rows'])
            return props
        elif isinstance(obj, RowProxy):
            return dict(obj)
        elif isinstance(obj, webob_dicts):
            return obj.mixed()
        else:
            return JSONEncoder.default(self, obj)
示例#16
0
 def default(self, obj):
     if hasattr(obj, '__json__') and callable(obj.__json__):
         return obj.__json__()
     elif isinstance(obj, (date, datetime)):
         return str(obj)
     elif isinstance(obj, Decimal):
           # XXX What to do about JSONEncoder crappy handling of Decimals?
           # SimpleJSON has better Decimal encoding than the std lib
           # but only in recent versions
         return float(obj)
     elif is_saobject(obj):
         props = {}
         for key in obj.__dict__:
             if not key.startswith('_sa_'):
                 props[key] = getattr(obj, key)
         return props
     elif isinstance(obj, ResultProxy):
         props = dict(rows=list(obj), count=obj.rowcount)
         if props['count'] < 0:
             props['count'] = len(props['rows'])
         return props
     elif isinstance(obj, RowProxy):
         return dict(obj)
     elif isinstance(obj, (MultiDict, UnicodeMultiDict)):
         return obj.mixed()
     else:
         return JSONEncoder.default(self, obj)
示例#17
0
文件: tags.py 项目: zagy/karl
def jquery_tag_del_view(context, request):
    value = request.params['val'].strip()
    value = value.decode('utf')
    del_tags(context, request, [value])
    status = {}
    result = JSONEncoder().encode(status)
    return Response(result, content_type="application/x-json")
 def handler(self, obj):
     if isinstance(obj, Decimal):
         return ('%.' + str(self.round_decimal_places) + 'f') % obj
     elif isinstance(obj, date):
         return obj.strftime('%Y-%m-%d')
     elif isinstance(obj, datetime):
         return obj.strftime('%Y-%m-%d %H:%I:%S')
     return JSONEncoder.default(self, obj)
 def handler(self, obj):
     if isinstance(obj, Decimal):
         return ('%.' + str(self.round_decimal_places) + 'f') % obj
     elif isinstance(obj, date):
         return obj.strftime('%Y-%m-%d')
     elif isinstance(obj, datetime):
         return obj.strftime('%Y-%m-%d %H:%I:%S')
     return JSONEncoder.default(self, obj)
示例#20
0
文件: tags.py 项目: zagy/karl
def tag_search_json_view(context, request):
    tag_query_tool = getMultiAdapter((context, request), ITagQuery)
    try:
        # Query parameter shall be 'term'.
        prefix = request.params['term']
    except UnicodeDecodeError:
        # not utf8, just return empty list since tags can't have these chars
        result = JSONEncoder().encode([])
        return Response(result, content_type="application/x-json")
    # case insensitive
    prefix = prefix.lower()
    values = tag_query_tool.tags_with_prefix(prefix)
    # uniterize
    values = list(values)
    # The return payload simply expects the list of labels.
    result = JSONEncoder().encode(values)
    return Response(result, content_type="application/x-json")
示例#21
0
 def serialize(object, human=False):
     if human:
         indent = 2
         sort_keys = True
     else:
         indent = None
         sort_keys = False
     return JSONEncoder(indent=indent,
                        sort_keys=sort_keys).encode(object)
示例#22
0
  def save_node_set(self, name, nodes):
	name = unquote(name)
	nodes = unquote(nodes)
	file_name = "nodes-sets.json"
	data = JSONDecoder().decode(file(file_name).read())
	data[name] = nodes
	open(file_name, "w").write(
		JSONEncoder(indent=4,sort_keys=1).encode(data))
	return {"name": name}
示例#23
0
 def default(self, obj):
     try:
         if isinstance(obj, Delivery) or isinstance(obj, Driver):
             return obj.to_dict()
         iterable = iter(obj)
     except TypeError:
         pass
     else:
         return list(iterable)
     return JSONEncoder.default(self, obj)
示例#24
0
 def default(self, obj):
     try:
         if isinstance(obj, datetime) or isinstance(obj, date):
             obj = obj.isoformat()
         iterable = iter(obj)
     except TypeError:
         pass
     else:
         return "".join(list(iterable))
     return JSONEncoder.default(self, obj)
示例#25
0
文件: widgets.py 项目: ocemr/ocemr
    def __init__(self, source, options={}, attrs={}):
        """source can be a list containing the autocomplete values or a
		string containing the url used for the XHR request. """

        self.options = {'source': source, 'minLength': '2', 'max': '64'}
        self.attrs = {'autocomplete': 'off'}
        if len(options) > 0:
            self.options = JSONEncoder().encode(options)

        self.attrs.update(attrs)
示例#26
0
    def encode(self, o):
        root_id = id(o)
        if self.check_circular:
            markers = {}
        else:
            markers = None

        def _encode(o):
            try:
                import pandas as pd
            except ImportError:
                pd = None

            if isinstance(o, (list, tuple, dict)):
                if markers is not None:
                    marker_id = id(o)
                    if marker_id in markers:
                        if marker_id == root_id:
                            return {"$ref": "#"}
                        raise ValueError("Circular reference detected")
                    markers[marker_id] = o
                try:
                    if isinstance(o, dict):
                        return {k: _encode(v) for k, v in o.items()}
                    else:
                        return [_encode(v) for v in o]
                finally:
                    if markers is not None:
                        del markers[marker_id]

            if isinstance(o, date):
                return {"$date": int(calendar.timegm(o.timetuple()) * 1000)}
            if isinstance(o, datetime):
                return {"$date": int(calendar.timegm(o.utctimetuple()) * 1000)}

            if isinstance(o, Reference):
                # FIXME if reference is not saved, save it first here
                return {"$ref": o._uri}

            try:
                if pd and pd.api.types.is_integer(o):
                    return int(o)
            except AttributeError:
                # some versions of pandas may not have this API
                pass

            try:
                if pd and pd.api.types.is_float(o):
                    return float(o)
            except AttributeError:
                pass

            return o

        return JSONEncoder.encode(self, _encode(o))
示例#27
0
 def getFinal(self, receiver):
     encrypted = self.__getCipherText()
     # encrypted = JSONEncoder().encode(encrypted)
     encryptedRSA = PgpHandler.RSAencrypt(self.publicKey,
                                          encrypted["AESkey"])
     obj = {
         "to": receiver,
         "cipher": encrypted["cipher"],
         "AESEncryptedKey": encryptedRSA
     }
     return JSONEncoder(separators=(',', ':')).encode(obj)
示例#28
0
文件: tags.py 项目: zagy/karl
def jquery_tag_add_view(context, request):
    value = request.params['val'].strip()
    value = value.decode('utf')
    add_tags(context, request, [value])
    status = {}
    # check for valid characters
    if not _validate_tag(value):
        # This will signal an error for the client.
        status['error'] = 'Adding tag failed, it contains illegal characters.'
    result = JSONEncoder().encode(status)
    return Response(result, content_type="application/x-json")
示例#29
0
    def test_raises_bad_request_when_rpc_params_are_invalid(self):
        from simplejson import JSONEncoder
        from pyramid.httpexceptions import HTTPBadRequest

        rpc_request = {'method': 'checkWords', 'params': ['en']}
        json = JSONEncoder().encode(rpc_request)

        request = testing.DummyRequest(method='POST',
                                       body=json,
                                       content_type='application/x-json')
        self.assertRaises(HTTPBadRequest, self._callFUT, request)
示例#30
0
 def default(self, o):  # pylint: disable=method-hidden
     if isinstance(o, Decimal):
         return float(o)
     if isinstance(o, (datetime.date, Amount, Position)):
         return str(o)
     if isinstance(o, (set, frozenset)):
         return list(o)
     try:
         return JSONEncoder.default(self, o)
     except TypeError:
         return str(o)
示例#31
0
def redis_single_zadd_pgpfc(user_id,
                            task_count,
                            file_id,
                            fsize,
                            psize,
                            ppc,
                            operation,
                            src,
                            priority,
                            server_host=None,
                            server_port=None):
    """
    推送到某个user id的task列表
    :param user_id:
    :param task_count: 任务份数
    :param file_id:
    :param fsize:
    :param psize:
    :param ppc:
    :param operation:
    :param src:
    :param priority:
    :param server_host:
    :param server_port:
    :return:
    """
    key = "PGPFC_" + str(user_id)
    if operation == "download":
        value = {
            "file_id": str(file_id),
            "fsize": int(fsize),
            "psize": int(psize),
            "ppc": int(ppc),
            "operation": str(operation),
            "src": src,
            "priority": int(priority)
        }
        if server_host is not None and server_port is not None:
            value["server"] = str(server_host)
            value["port"] = int(server_port)
    elif operation == "delete":
        value = {
            "file_id": str(file_id),
            "psize": int(psize),
            "ppc": int(ppc),
            "operation": str(operation),
            "src": src,
            "priority": int(priority)
        }
    else:
        raise
    # 将dict转成json格式
    value = JSONEncoder().encode(value)
    rc.zadd(key, task_count, value)
示例#32
0
文件: utils.py 项目: zagy/karl
def convert_to_script(data, var_name='_karl_client_data'):
    if data:
        ##print data
        result = JSONEncoder().encode(data)
        script = dedent("""\
            <script type="text/javascript">
            window.%s = %s;
            </script>""" % (var_name, result))
    else:
        # no data, no script.
        script = ''
    return script
 def default(self, obj):
     if isinstance(obj, QuerySet):
         # TODO - follow relations.
         # See: https://code.djangoproject.com/ticket/4656
         return loads(serialize('json', obj))
     elif isinstance(obj, Decimal):
         return ('%.' + str(self.round_decimal_places) + 'f') % obj
     elif isinstance(obj, datetime):
         return obj.strftime('%Y-%m-%d %H:%I:%S')
     elif isinstance(obj, date):
         return obj.strftime('%Y-%m-%d')
     return JSONEncoder.default(self, obj)
 def default(self, obj):
     if isinstance(obj, QuerySet):
         # TODO - follow relations.
         # See: https://code.djangoproject.com/ticket/4656
         return loads(serialize('json', obj))
     elif isinstance(obj, Decimal):
         return ('%.' + str(self.round_decimal_places) + 'f') % obj
     elif isinstance(obj, datetime):
         return obj.strftime('%Y-%m-%d %H:%I:%S')
     elif isinstance(obj, date):
         return obj.strftime('%Y-%m-%d')
     return JSONEncoder.default(self, obj)
示例#35
0
def lpush_rrpc_leave_lf(redis_single_host, redis_single_port, stun_ip, file_id, peer_ids):
    rc = redis.StrictRedis(host=redis_single_host, port=redis_single_port, db=0)
    RRPC_KEY = "RRPC_" + str(stun_ip)
    if type(peer_ids) is not list: peer_ids = [peer_ids]
    value = {
        "cmd": "leave_lf",
        "file_id": str(file_id),
        "peer_ids": peer_ids
    }
    # 将dict转成json格式
    value = JSONEncoder().encode(value)
    rc.lpush(RRPC_KEY, value)
    def readjsonstructure(self, project_id, visibility_filter=StaticFiltersFactory.FULL_VIEW,
                          first_level=None, second_level=None, filter_value=None):
        """
        AJAX exposed method. 
        Will return the complete JSON for Project's structure, or filtered tree
        (filter only Relevant entities or Burst only Data).
        """
        if first_level is None or second_level is None:
            first_level, second_level = self.get_project_structure_grouping()
        else:
            self.set_project_structure_grouping(first_level, second_level)

        selected_filter = StaticFiltersFactory.build_datatype_filters(single_filter=visibility_filter)

        project = self.project_service.find_project(project_id)
        json_structure = self.project_service.get_project_structure(project, selected_filter,
                                                                    first_level, second_level, filter_value)
        # This JSON encoding is necessary, otherwise we will get an error
        # from JSTree library while trying to load with AJAX 
        # the content of the tree.     
        encoder = JSONEncoder()
        return encoder.iterencode(json_structure)
示例#37
0
    def test_renders_suggestions_for_getSuggestions_request(self):
        from simplejson import JSONEncoder
        rpc_request = {
            'id': None,
            'method': 'getSuggestions',
            'params': ['en', 'foo']
        }
        json = JSONEncoder().encode(rpc_request)

        request = testing.DummyRequest(method='POST', body=json)
        data = self._callFUT(testing.DummyModel(), request)
        self.assertEquals(data['id'], None)
        self.assertEquals(data['result'], ['foo', 'foo', 'foo'])
        self.assertEquals(data['error'], None)
示例#38
0
    def encode(self, o):
        root_id = id(o)
        if self.check_circular:
            markers = {}
        else:
            markers = None

        def _encode(o):
            if isinstance(o, (list, tuple, dict)):
                if markers is not None:
                    marker_id = id(o)
                    if marker_id in markers:
                        if marker_id == root_id:
                            return {"$ref": "#"}
                        raise ValueError("Circular reference detected")
                    markers[marker_id] = o
                try:
                    if isinstance(o, dict):
                        return {k: _encode(v) for k, v in o.items()}
                    else:
                        return [_encode(v) for v in o]
                finally:
                    if markers is not None:
                        del markers[marker_id]

            if isinstance(o, date):
                return {"$date": int(calendar.timegm(o.timetuple()) * 1000)}
            if isinstance(o, datetime):
                return {"$date": int(calendar.timegm(o.utctimetuple()) * 1000)}

            if isinstance(o, Reference):
                # FIXME if reference is not saved, save it first here
                return {"$ref": o._uri}

            try:
                if pd and pd.api.types.is_integer(o):
                    return int(o)
            except AttributeError:
                # some versions of pandas may not have this API
                pass

            try:
                if pd and pd.api.types.is_float(o):
                    return float(o)
            except AttributeError:
                pass

            return o

        return JSONEncoder.encode(self, _encode(o))
示例#39
0
    def test_renders_error_response_for_unsupported_language(self):
        from simplejson import JSONEncoder
        rpc_request = {
            'id': None,
            'method': 'checkWords',
            'params': ['za', ['foo', 'bar']]
        }
        json = JSONEncoder().encode(rpc_request)

        request = testing.DummyRequest(method='POST', body=json)
        data = self._callFUT(testing.DummyModel(), request)
        self.assertEquals(data['id'], None)
        self.assertEquals(data['result'], [])
        self.assertEquals(data['error'], 'Language is not supported')
示例#40
0
    def test_renders_misspelled_words_for_checkWords_request(self):
        from simplejson import JSONEncoder
        rpc_request = {
            'id': None,
            'method': 'checkWords',
            'params': ['en', ['foo', 'bar']]
        }
        json = JSONEncoder().encode(rpc_request)

        request = testing.DummyRequest(method='POST', body=json)
        data = self._callFUT(testing.DummyModel(), request)
        self.assertEquals(data['id'], None)
        self.assertEquals(data['result'], ['foo', 'bar'])
        self.assertEquals(data['error'], None)
示例#41
0
 def default(self, obj):
     if hasattr(obj, '__json__') and callable(obj.__json__):
         return obj.__json__()
     elif isinstance(obj, (datetime.date, datetime.datetime)):
         return str(obj)
     elif isinstance(obj, decimal.Decimal):
         return float(obj)
     elif isinstance(obj, MultiDict):
         return obj.mixed()
     elif isinstance(obj, Mapping):
         return dict(obj)
     elif isinstance(obj, uuid.UUID):
                     return str(obj)
     else:
         return JSONEncoder.default(self, obj)
示例#42
0
 def default(self, obj):
     if hasattr(obj, '__json__'):
         return obj.__json__()
     elif isinstance(obj, (datetime.date, datetime.datetime)):
         return str(obj)
     elif isinstance(obj, decimal.Decimal):
         return float(obj)
     elif is_saobject(obj):
         props = {}
         for prop in object_mapper(obj).iterate_properties:
             if not hasattr(prop, 'uselist'):
                 props[prop.key] = getattr(obj, prop.key)
         return props
     elif isinstance(obj, ResultProxy):
         return list(obj)
     elif isinstance(obj, RowProxy):
         return dict(obj)
     else:
         return JSONEncoder.default(self, obj)
示例#43
0
文件: jsonify.py 项目: kamroot/mc27
 def default(self, obj):
     if hasattr(obj, '__json__') and callable(obj.__json__):
         return obj.__json__()
     elif isinstance(obj, (datetime.date, datetime.datetime)):
         return str(obj)
     elif isinstance(obj, decimal.Decimal):
         return float(obj)
     elif is_saobject(obj):
         props = {}
         for key in obj.__dict__:
             if not key.startswith('_sa_'):
                 props[key] = getattr(obj, key)
         return props
     elif isinstance(obj, ResultProxy):
         return dict(rows=list(obj), count=obj.rowcount)
     elif isinstance(obj, RowProxy):
         return dict(rows=dict(obj), count=1)
     elif isinstance(obj, MultiDict):
         return obj.mixed()
     else:
         return JSONEncoder.default(self, obj)
示例#44
0
文件: dejavuJSON.py 项目: CarlFK/dabo
	def default(self, o):
		_special_types = (datetime.date, datetime.time, datetime.datetime,
						  decimal.Decimal)
		# We MUST check for a datetime.datetime instance before datetime.date.
		# datetime.datetime is a subclass of datetime.date, and therefore
		# instances of it are also instances of datetime.date.
		if isinstance(o, datetime.datetime) or o is datetime.datetime:
			if o is datetime.datetime:
				o = Null()
			return {'__datetime__': True,
					'value': o.strftime(self.DATETIME_FMT)}

		if isinstance(o, datetime.date) or o is datetime.date:
			if o is datetime.date:
				o = Null()
			return {'__date__': True,
					'value': o.strftime(self.DATE_FMT)}

		if isinstance(o, datetime.time) or o is datetime.time:
			if o is datetime.time:
				o = Null()
			return {'__time__': True,
					'value': o.strftime(self.TIME_FMT)}

		if isinstance(o, decimal.Decimal) or o is decimal.Decimal:
			if o is decimal.Decimal:
				value = None
			else:
				value = str(o)
			return {'__decimal__': True,
					'value': value}

		if isinstance(o, Null):
			return None

		else:
			return JSONEncoder.default(self, o)
示例#45
0
from zojax.content.type.interfaces import IContentType
from zojax.formatter.interfaces import IFormatterConfiglet
from zojax.personal.space.interfaces import IPersonalSpace
from zojax.principal.profile.interfaces import IPersonalProfile
from zojax.resourcepackage.library import include, includeInplaceSource
from zojax.authentication.utils import getPrincipal
from zojax.principal.profile.timezone import getPrincipalTimezone
from zojax.principal.field.utils import searchPrincipals


class Encoder(JSONEncoder):

    def encode(self, *kv, **kw):
        return unicode(super(Encoder, self).encode(*kv, **kw))

encoder = JSONEncoder()


def jsonable(func):

    def cal(self):
        self.request.response.setHeader('Content-Type', ' application/json;charset=UTF-8')
        return unicode(func(self)).encode('utf-8')
    return cal


def js2PythonTime(value, diffHours=None):
    """ converts str date to datetime """
    try:
        value = datetime.strptime(value, '%m/%d/%Y %H:%M')
    except ValueError:
示例#46
0
文件: json.py 项目: jfred/nudge
 def default(self, o):
     if hasattr(o, "json"):
         return getattr(o, "json")()
     if isinstance(o, datetime.datetime):
         return o.ctime()
     return JSONEncoder.default(self, o)
示例#47
0
文件: __init__.py 项目: Afey/pyjs
 def default(self, obj):
     if isinstance(obj, JSONRPCError):
         return obj.__class__.__name__
     else:
         return JSONEncoder.default(self, obj)
示例#48
0
from zojax.content.attachment.image import Image
from zojax.content.attachment.media import Media
from zojax.content.attachment.interfaces import IImage, IMedia
from zope.app.component.hooks import getSite

from zojax.filefield.data import getImageSize
from zojax.filefield.interfaces import NotAllowedFileType


class Encoder(JSONEncoder):

    def encode(self, *kv, **kw):
        return unicode(super(Encoder, self).encode(*kv, **kw))

encoder = JSONEncoder()


def jsonable(func):

    def cal(self):
        self.request.response.setHeader('Content-Type', ' application/json')
        return unicode(func(self)).encode('utf-8')
    return cal


class IImageManagerAPI(interface.Interface):
    pass


class IMediaManagerAPI(interface.Interface):
示例#49
0
 def default(self, o):
     if type(o) not in [str, unicode, dict, list]:
         return str(o)
     return JSONEncoder.default(self, o)
示例#50
0
 def default(self, obj):
     if isinstance(obj, Transmittable):
         return obj.to_obj()
     return JSONEncoder.default(self, obj)
         
     
示例#51
0
文件: json.py 项目: dominicgs/Website
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat(' ')

        return JSONEncoder.default(self, obj)
 def default(self, o):
     if type(o) is Hit:
         d = {"__class__": Hit.__name__}
         d.update(o.__dict__)
         return d
     return JSONEncoder.default(self, o)
 def default(self, o):
     if hasattr(o, '__iter__'):
         return StreamArray(o)
     else:  # pragma: no cover
         return JSONEncoder.default(self, o)
示例#54
0
from __future__ import with_statement
import fs, re, fileinput
from os.path import join,isdir,exists

from thepian.conf import structure

from simplejson import JSONEncoder
encoder = JSONEncoder()

scope_statement = re.compile(r'@scope [^"]*"([^"]+)"')
requires_statement = re.compile(r'@requires [^"]*"([^"]+)"')

class SourceNode(object):
    
    used = False
    
    def __init__(self,path,basedir,source=None,lines=None,attributes={}):
        """
        Loads the source code for the node from *path* unless *source* is specified.
        Then determines scope, includes and requires
        
        source Optional string with inline source code
        """
        self.path = path
        self.basedir = basedir
        self.scope = None
        if lines:
            self._lines = lines
        elif source is None:
            try:
                self._lines = [line for line in fileinput.FileInput(files=(self.path,))]
示例#55
0
 def __init__(self, db):
     JSONEncoder.__init__(self)
     self.db = db