Ejemplo n.º 1
0
 def __init__(self, *args, **kwargs):
     kwargs.pop('namedtuple_as_object', None)
     kwargs.pop('use_decimal', None)
     kwargs.pop('item_sort_key', None)
     kwargs.pop('for_json', None)
     kwargs.pop('bigint_as_string', None)
     kwargs.pop('tuple_as_array', None)
     kwargs.pop('ignore_nan', None)
     DjangoJSONEncoder.__init__(self, *args, **kwargs)
Ejemplo n.º 2
0
def encode_task_to_json(task):
	"""
	Encode Task to a JSON serialisable object.
	"""
	datetime_json_encoder = DjangoJSONEncoder()
	
	return {'id': task.id,
			'date': datetime_json_encoder.encode(task.date),
			'notes': task.notes,}
Ejemplo n.º 3
0
def json_v1(req):
    enc = DjangoJSONEncoder(
        ensure_ascii=False, indent=2, separators=(',', ':'))
    return HttpResponse(enc.encode(
        [
            info.toolinfo()
            for info in ToolInfo.objects.all().order_by('name')
        ]),
        content_type="application/json; charset=utf8"
    )
Ejemplo n.º 4
0
 def get_context_data(self, **kwargs):
     data = super(MarketDetail, self).get_context_data(**kwargs)
     serializer = DjangoJSONEncoder()
     stations = (self.object.stations.filter(active=True)
         .order_by('-latest_snapshot__timestamp')
         .select_related('latest_snapshot')
     )
     data['stations'] = stations
     json_data = {
         'stations': map(self.station_to_json, stations),
         'updated_at': stations[0].updated_at,
     }
     data['station_json'] = serializer.encode(json_data)
     return data
Ejemplo n.º 5
0
    def default(self, obj):

        """
        Enable serialisation of a ValuesQuerySet

        This function must return a serializable object for any object type it
        receives. ValuesQuerySet will return dictionaries when used as an
        iterable. Here we differentiate between a ValuesQuerySet with one or
        more items and return either a dictionary/list of dictionaries.

        You can test ajax queries from the terminal with:
        $ curl -H 'X-Requested-With: XMLHttpRequest' <url>

        Serialising querysets - returns a multiple item list
        if isinstance(obj, QuerySet):
            return json.loads(serializers.serialize('json', obj))
        
        Serialising models - returns a single item list
        if isinstance(obj, models.Model):
            obj = [obj] # Iterable required
            return json.loads(serializers.serialize("json", obj))[0]
        """

        if isinstance(obj, ValuesQuerySet):
            if len(obj) > 0:
                return list(obj)
            else:
                return list(obj)[0]
        return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 6
0
def encode_event_to_json(event):
	"""
	Encode Event to a JSON serialisable object.
	"""
	datetime_json_encoder = DjangoJSONEncoder()
	
	return {'id': event.id,
			'title': event.title,
			'from_date': datetime_json_encoder.encode(event.from_date),
			'from_time': datetime_json_encoder.encode(event.from_time),
			'to_date': datetime_json_encoder.encode(event.to_date),
			'to_time': datetime_json_encoder.encode(event.to_time),
			'location': event.location,
			'note': event.note,
			'lecturer': '%s' % event.lecturer,
			'module': '%s' % event.module,}
Ejemplo n.º 7
0
 def default(self, obj):
     if isinstance(obj, QuerySet):
         return json.loads(serialize('json', obj))
     elif isinstance(obj, Model):
         return json.loads(serialize('json', [obj]))[0]
     else:
         return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 8
0
 def default(self, obj):
     impl = getattr(obj, to_json_implementation, None)
     if impl and callable(impl):
         return impl()
     if hasattr(obj, 'isoformat'):
         return obj.isoformat()
 
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 9
0
    def save(self, old_record, list_record, detail_record):
        license_type = self.get_or_create_lookup(
            'license_type',
            list_record['license_type_code'],
            list_record['license_type_code'],
            make_text_slug=False)
        disposition = self.get_or_create_lookup('disposition',
                                                list_record['disposition'],
                                                list_record['disposition'],
                                                make_text_slug=False)
        violation_lookups = [
            self.get_or_create_lookup('violation',
                                      v[0],
                                      v[0],
                                      make_text_slug=False)
            for v in list_record['violations']
        ]
        violation_lookup_text = ','.join(
            [str(v.id) for v in violation_lookups])

        v_lookup_dict = dict([(v.code, v.id) for v in violation_lookups])
        v_list = [{
            'lookup_id': v_lookup_dict[code],
            'number': number
        } for code, number in list_record['violations']]
        details_json = DjangoJSONEncoder().encode(v_list)

        title = u'%s inspected: %s violation%s' % (
            list_record['business_name'], list_record['total_violations'],
            list_record['total_violations'] != 1 and 's' or '')

        values = {
            'title':
            title,
            'item_date':
            list_record['inspection_date'],
            'location_name':
            '%s, %s' % (list_record['address'], list_record['city']),
        }
        attributes = {
            'inspection_visit_id': list_record['inspection_visit_id'],
            'license_id': list_record['license_id'],
            'license_number': list_record['license_number'],
            'business_name': list_record['business_name'],
            'inspection_number': list_record['inspection_number'],
            'license_type': license_type.id,
            'critical_violations': list_record['critical_violations'],
            'noncritical_violations': list_record['noncritical_violations'],
            'total_violations': list_record['total_violations'],
            'visit_number': list_record['visit_number'],
            'disposition': disposition.id,
            'violation': violation_lookup_text,
            'violation_details': details_json,
        }
        if old_record is None:
            self.create_newsitem(attributes, **values)
        else:
            self.update_existing(old_record, values, attributes)
Ejemplo n.º 10
0
def get_models(result):
    encoder = DjangoJSONEncoder()
    content = []
    for e in result:
        rep = ""
        if hasattr(e, "__unicode__"):
            rep = e.__unicode__()
        else:
            rep = e.__str__()
        fields = {"repr": rep}
        
        for f in e._meta.fields:            
            try:
                fields[f.name] = encoder.default(getattr(e, f.name))
            except:
                fields[f.name] = getattr(e, f.name)        
        content.append(fields)
    return content
Ejemplo n.º 11
0
    def default(self, obj):

        if type(obj) == QuerySet:
            return serializers.serialize("python", obj, ensure_ascii=False)

        if type(obj) == EmptyQuerySet:
            return serializers.serialize("python", obj, ensure_ascii=False)

        return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 12
0
def poll_specifications(sandbox_pk: int) -> None:
    """Poll specifications of a sandbox and send it to the correct group."""
    sandbox = Sandbox.objects.get(pk=sandbox_pk)
    sandbox_specs, container_specs = async_to_sync(
        sandbox.poll_specifications)()
    channel_layer = get_channel_layer()

    async_to_sync(channel_layer.group_send)(
        f"sandbox_sandbox_specs_{sandbox_pk}", {
            'type': 'sandbox_specs',
            'specs': DjangoJSONEncoder().encode(dgeq.serialize(sandbox_specs))
        })
    async_to_sync(channel_layer.group_send)(
        f"sandbox_container_specs_{sandbox_pk}", {
            'type': 'container_specs',
            'specs': DjangoJSONEncoder().encode(
                dgeq.serialize(container_specs))
        })
Ejemplo n.º 13
0
 def handle_object(self, object, fields=None, exclude=None):
     """ Called to handle everything, looks for the correct handling """
     # print type(object)
     # print object
     # print inspect.isclass(object)
     # print inspect.ismethod(object)
     # print inspect.isfunction(object)
     # print inspect.isbuiltin(object)
     # print inspect.isroutine(object)
     # print inspect.isabstract(object)
     # print type(object) == 'staticmethod'
     if (inspect.isroutine(object) or inspect.isbuiltin(object)
             or inspect.isclass(object)):
         raise UnableToSerializeMethodTypesError(type(object))
     elif isinstance(object, dict):
         return self.handle_dictionary(object)
     elif (isinstance(object, list) or isinstance(object, tuple)
           or isinstance(object, set)):
         return self.handle_list(object)
     elif isinstance(object, Model):
         if hasattr(object, 'serialize'):
             exclude = self.exclude
             return self.handle_object(
                 getattr(object, 'serialize')(fields, exclude), fields,
                 exclude)
         else:
             return self.handle_model(object, fields, self.exclude)
         #return PythonSerializer().serialize([object],**self.options.copy())[0]['fields']
     elif isinstance(object, QuerySet):
         #return super(JSONSerializer,self).serialize(object, **self.options.copy())[0]
         ret = []
         for item in object:
             ret.append(self.handle_object(item, fields, exclude))
         return ret
     elif (isinstance(object, int) or isinstance(object, float)
           or isinstance(object, long) or isinstance(object, basestring)
           or isinstance(object, bool) or object is None):
         return object
     elif (isinstance(object, datetime.datetime)
           or isinstance(object, datetime.date)
           or isinstance(object, datetime.time)
           or isinstance(object, decimal.Decimal)):
         return DjangoJSONEncoder().default(object)
     elif isinstance(object, GEOSGeometry):
         return getattr(object, self.geom_format)
     elif isinstance(object, File):
         return object.name
     elif isinstance(object, uuid.UUID):
         return str(object)
     elif hasattr(object, '__dict__'):
         # call an objects serialize method if it exists
         if hasattr(object, 'serialize'):
             return getattr(object, 'serialize')()
         else:
             return self.handle_dictionary(object.__dict__)
     else:
         raise UnableToSerializeError(type(object))
Ejemplo n.º 14
0
 def default(self, obj):
     #Add the ability to deal with timedelta
     if isinstance(obj, timedelta):
         ARGS = ('days', 'seconds', 'microseconds')
         #So if we get a time-delta object return a dictionary with type and a list of the day, second, microseconds
         return {'__type__': 'datetime.timedelta',
                 'args': [getattr(obj, a) for a in ARGS]}
     if isinstance(obj, QuerySet):
         return [item for item in obj]
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 15
0
 def default(self, value):
     if isinstance(value, datetime.date):
         return DjangoJSONEncoder.default(self, value)
     if isinstance(value, bytes):
         def bool_from_byte(byte_value):
             return 1 if byte_value == b'\x01' else 0
         return bool_from_byte(value)
     if isinstance(value, Decimal):
         return float(value)
     else:
         return value.__dict__
Ejemplo n.º 16
0
 def default(self, obj):
     if isinstance(obj, Matrix):
         return {
             "__matrix__": True,
             "cols": obj.cols,
             "width": obj.width,
             "rows": obj.rows,
             "height": obj.height,
             "matrix": obj.matrix.items(),
         }
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 17
0
 def __init__(self,
              verbose_name=None,
              name=None,
              encoder=DjangoJSONEncoder(),
              **kwargs):
     models.TextField.__init__(self,
                               verbose_name,
                               name,
                               blank=True,
                               **kwargs)
     self.encoder = encoder
Ejemplo n.º 18
0
 def default(self, obj):
     if isinstance(obj, Decimal):
         return float(obj)
     if isinstance(obj, datetime.datetime):
         return obj.strftime('%Y-%m-%d %H:%M:%S')
     if isinstance(obj, datetime.date):
         return obj.strftime('%Y-%m-%d')
     else:
         if type(obj)==ipaddr.IPv4Network or  type(obj)==ipaddr.IPAddress:
             return str(obj)
         return DjangoJSONEncoder().default(obj)
Ejemplo n.º 19
0
def poll_usage(sandbox_pk: int) -> None:
    """Poll usage of a sandbox and send it to the correct group."""
    sandbox = Sandbox.objects.get(pk=sandbox_pk)
    usage = async_to_sync(sandbox.poll_usage)()
    channel_layer = get_channel_layer()

    async_to_sync(channel_layer.group_send)(
        f"sandbox_usage_{sandbox_pk}", {
            'type': 'sandbox_usage',
            'usage': DjangoJSONEncoder().encode(dgeq.serialize(usage))
        })
Ejemplo n.º 20
0
def _render_app_html(request, initial_json):
    html = loader.render_to_string('app.html')

    html = html.replace(
        "window.initialJSON=null", "window.initialJSON=" +
        json.dumps(initial_json, default=DjangoJSONEncoder().default))

    if request.get_host() == 'localhost:3000':
        html = re.sub(r'static/app(-.*)js', 'app.js', html)
        html = re.sub(r'<link\s+href="/static/app.*css"[^>]*>', '', html)

    return HttpResponse(html, content_type="text/html")
Ejemplo n.º 21
0
 def __init__(self,
              verbose_name=None,
              name=None,
              encoder=DjangoJSONEncoder(),
              **kwargs):
     blank = kwargs.pop('blank', True)
     models.TextField.__init__(self,
                               verbose_name,
                               name,
                               blank=blank,
                               **kwargs)
     self.encoder = encoder
Ejemplo n.º 22
0
 def test_get_single(self):
     response = self.client.get(
         reverse("pl_sandbox:request-detail", args=(self.request.pk, )))
     # Encode and decode the expected output so that the date format match
     expected = json.loads(DjangoJSONEncoder().encode({
         "status":
         True,
         "row":
         dgeq.serialize(self.request),
     }))
     self.assertEqual(200, response.status_code)
     self.assertEqual(expected, response.json())
Ejemplo n.º 23
0
 def create_set(self, project, json_data=None, **options):
     """Create a new articleset. Provide the needed arguments using the post_data or with key-value pairs"""
     url = articleset_url.format(**locals())
     if json_data is None:
         # form encoded request
         return self.request(url, method="post", data=options)
     else:
         if not isinstance(json_data, (str, unicode)):
             
             json_data = DjangoJSONEncoder().encode(json_data)
         headers = {'content-type': 'application/json'}
         return self.request(url, method='post', data=json_data, headers=headers)
Ejemplo n.º 24
0
def serialize(obj):
    if isinstance(obj, Mapping):
        for k, v in obj.items():
            obj[k] = serialize(v)
    elif isinstance(obj, Collection) and not isinstance(obj, str):
        for i in obj:
            i = serialize(i)
    elif isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
        obj = DjangoJSONEncoder().default(obj)
    elif isinstance(obj, decimal.Decimal):
        obj = float(obj)  # DjangoJSONEncoder().default(obj)
    return obj
Ejemplo n.º 25
0
 def default(self, obj):
     if isinstance(obj, models.Model):
         if self.__serializable__(obj):
             return obj.serialize()
         else:
             return loads(serialize('json', obj))
     if isinstance(obj, QuerySet):
         list = []
         for o in obj:
             list.append(o.serialize())
         return list
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 26
0
 def default(self, obj):
     if isinstance(obj, models.Model):
         if self.__serializable__(obj):
             return obj.serialize()
         else:
             return loads(serialize('json', obj))
     if isinstance(obj, QuerySet):
         list = []
         for o in obj:
             list.append(o.serialize())
         return list
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 27
0
 def default(self, obj, **kwargs):
     if isinstance(obj, date):
         return str(obj)
     elif isinstance(obj, models.Model):
         return model_to_dict(obj)
     elif isinstance(obj, ImageFieldFile):
         if obj:
             return obj.url
         return None
     elif isinstance(obj, Decimal):
         return str(obj)
     else:
         return DjangoJSONEncoder.default(obj, **kwargs)
Ejemplo n.º 28
0
 def default(self, obj):
     """Add the ability to deal with timedelta"""
     if isinstance(obj, timedelta):
         args = ('days', 'seconds', 'microseconds')
         # So if we get a time-delta object return a dictionary with
         # type and a list of the day, second, microseconds
         return {
             '__type__': 'datetime.timedelta',
             'args': [getattr(obj, arg) for arg in args]
         }
     if isinstance(obj, QuerySet):
         return list(obj)
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 29
0
 def wrapper(**kwargs):
     with atomic():
         # We can get a hold of the log entry here and provide it to all
         # operations, return it, connect it to higher-level operations (we can
         # detect that this is a nested action).
         log = DataLog.objects.create(
             # We could also include the idea of adding an object's hash and
             # use it to prevent parallel operations on the same object, but
             # the calling code would be responsible of passing it here.
             operation_name=action_func.__name__,
             data=DjangoJSONEncoder().encode(kwargs),
         )
         return action_func(**kwargs)
Ejemplo n.º 30
0
    def save(self, old_record, list_record, detail_record):
        if old_record is not None:
            return  # We already have this inspection.

        restaurant_type = self.get_or_create_lookup(
            'restaurant_type', list_record['restaurant_type'],
            list_record['restaurant_type'])
        violation_lookups = [
            self.get_or_create_lookup('violation',
                                      v[0],
                                      v[0],
                                      make_text_slug=False)
            for v in list_record['violation_list']
        ]
        violation_lookup_text = ','.join(
            [str(v.id) for v in violation_lookups])

        # There's a bunch of data about every particular violation, and we
        # store it as a JSON object. Here, we create the JSON object.
        v_lookup_dict = dict([(v.code, v) for v in violation_lookups])
        v_list = [{
            'lookup_id': v_lookup_dict[code].id,
            'comment': comment
        } for code, comment in list_record['violation_list']]
        details_json = DjangoJSONEncoder().encode({
            'notes': list_record['notes'],
            'violations': v_list
        })

        title = u'%s inspected: ' % list_record['restaurant_name']
        if not list_record['violation_list']:
            title += u'No critical violations'
        else:
            num = len(list_record['violation_list'])
            title += u'%s critical violation%s' % (num, num != 1 and 's' or '')

        attributes = {
            'raw_address': list_record['raw_address'],
            'raw_city': list_record['raw_city'],
            'restaurant_hash': list_record['restaurant_hash'],
            'details': details_json,
            'restaurant_name': list_record['restaurant_name'],
            'restaurant_type': restaurant_type.id,
            'violation': violation_lookup_text,
        }
        self.create_newsitem(
            attributes,
            title=title,
            item_date=list_record['inspection_date'],
            location_name=list_record['address'],
        )
Ejemplo n.º 31
0
    def default(self, value):
        if isinstance(value, datetime.date):
            return DjangoJSONEncoder.default(self, value)
        elif isinstance(value, bytes):

            def bool_from_byte(byte_value):
                return 1 if byte_value == b'\x01' else 0

            return bool_from_byte(value)
        else:
            value_to_return = value.__dict__
            if '_state' in value_to_return.keys():
                del value_to_return['_state']
            return value_to_return
Ejemplo n.º 32
0
def default(o):
    if isinstance(o, models.Model):
        return o.pk

    if isinstance(o, models.QuerySet):
        return list(o.values_list('pk', flat=True))

    if isinstance(o, (Generator, set)):
        return list(o)

    if hasattr(o, '__json__'):
        return o.__json__()

    return DjangoJSONEncoder().default(o)
Ejemplo n.º 33
0
def serialize_personal_quiz(microlearning_average):
    json_encoder = DjangoJSONEncoder()
    project = microlearning_average.get_project()

    step_microlearnings = MicroLearning.objects.filter_by_step(
        microlearning_average.step)
    teams = project.teams.all()

    # Old version socket data
    serialized_data = microlearning_average.serialize()

    # Append data for new socket version
    serialized_data['personalRating'] = serialized_data.get('user')
    serialized_data['teamRatings'] = []

    for microlearning in step_microlearnings:
        for team in teams.filter(stream=microlearning.step_stream.stream):
            team_microlearning_avg = MicroLearningAverage(
                step_stream=microlearning.step_stream,
                user=None,
                team=team
            )
            data = team_microlearning_avg.serialize()
            serialized_data['teamRatings'].append(
                json.loads(
                    json_encoder.encode({
                        'pkTeam': team.pk,
                        'nameTeam': team.name,
                        'ratings': data.get('ratings'),
                        'avg': data.get('allTeamAvg'),
                    })
                )
            )
    serialized_data['teamRatings'] = sorted(
        serialized_data['teamRatings'], key=lambda x: x['pkTeam'])
    return serialized_data
Ejemplo n.º 34
0
    def create_articles(self, project, articleset, json_data=None, **options):
        """Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs

        json_data can be a dictionary or list of dictionaries. Each dict can contain a 'children' attribute which
        is another list of dictionaries. 
        """
        url = article_url.format(**locals())
        if json_data is None: #TODO duplicated from create_set, move into requests (or separate post method?)
            # form encoded request
            return self.request(url, method="post", data=options)
        else:
            if not isinstance(json_data, (str, unicode)):
                json_data = DjangoJSONEncoder().encode(json_data)
            headers = {'content-type': 'application/json'}
            return self.request(url, method='post', data=json_data, headers=headers)
Ejemplo n.º 35
0
    def get_or_create(self, table_name, **fields):
        """ Check if a resource exists in and if so return it.
        If it does not exist, create the resource and return it. """

        try:
            return self.get(table_name, **fields)
        except NotFoundError:
            pass

        for field_name, field_value in fields.iteritems():
            fields[field_name] = eval(DjangoJSONEncoder().encode(field_value))

        return self.coreapi_client.action(self.coreapi_schema,
                                          [table_name, "create"],
                                          params=fields)
Ejemplo n.º 36
0
    def get(self, request, **kwargs):
        del_window = datetime.timedelta(hours=12)
        serializer = DjangoJSONEncoder()
        station = self.model.objects.get(market__slug=kwargs['slug'],
                slug=kwargs['station_slug'])

        # make querysets
        recent_start = timezone.now() - datetime.timedelta(hours=11)
        recent_qs = station.history.filter(
            timestamp__gt=recent_start,
            timestamp__lte=recent_start + del_window,
        )
        yesterday_start = recent_start - datetime.timedelta(days=1)
        yesterday_qs = station.history.filter(
            timestamp__gt=yesterday_start,
            timestamp__lte=yesterday_start + del_window,
        )
        lastweek_start = recent_start - datetime.timedelta(days=7)
        lastweek_qs = station.history.filter(
            timestamp__gt=lastweek_start,
            timestamp__lte=lastweek_start + del_window,
        )

        # convert querysets to json
        recent = map(self.snapshot_to_json, recent_qs)
        yesterday = map(self.snapshot_to_json, yesterday_qs)
        lastweek = map(self.snapshot_to_json, lastweek_qs)

        data = {
            'capacity': station.capacity,
            'recent': recent,
            'yesterday': yesterday,
            'lastweek': lastweek,
        }
        return HttpResponse(serializer.encode(data),
                content_type='application/json')
Ejemplo n.º 37
0
def main_app(request, *args, **kwargs):
    """Loads the react single page app."""

    html = loader.render_to_string('app.html')

    html = html.replace(
        "window.initialJSON=null", "window.initialJSON=" +
        json.dumps({'user': _get_json_for_user(request.user)},
                   default=DjangoJSONEncoder().default))

    if request.get_host() == 'localhost:3000':
        html = re.sub(r'static/app(-.*)js', 'app.js', html)
        html = re.sub(r'<link\s+href="/static/app.*css"[^>]*>', '', html)

    return HttpResponse(html, content_type="text/html")
Ejemplo n.º 38
0
    def encode(self, o, *args, **kwargs):
        from djblets.webapi.resources import get_resource_for_object

        if isinstance(o, QuerySet):
            return list(o)

        resource = get_resource_for_object(o)

        if resource:
            return resource.serialize_object(o, *args, **kwargs)

        try:
            return DjangoJSONEncoder().default(o)
        except TypeError:
            return None
Ejemplo n.º 39
0
class WebsocketBindingWithMembers(WebsocketBinding):
    """
    Outgoing binding binding subclass based on WebsocketBinding.
    Additionally enables sending of member variables, properties and methods.
    Member methods can only have self as a required argument.
    Just add the name of the member to the send_members-list.
    Example:

    class MyModel(models.Model):
        my_field = models.IntegerField(default=0)
        my_var = 3

        @property
        def my_property(self):
            return self.my_var + self.my_field

        def my_function(self):
            return self.my_var - self.my_vield

    class MyBinding(BindingWithMembersMixin, WebsocketBinding):
        model = MyModel
        stream = 'mystream'

        send_members = ['my_var', 'my_property', 'my_function']
    """

    model = None
    send_members = []

    encoder = DjangoJSONEncoder()

    def serialize_data(self, instance):
        data = super(WebsocketBindingWithMembers,
                     self).serialize_data(instance)
        member_data = {}
        for m in self.send_members:
            member = instance
            for s in m.split('.'):
                member = getattr(member, s)
            if callable(member):
                member_data[m.replace('.', '__')] = member()
            else:
                member_data[m.replace('.', '__')] = member
        member_data = json.loads(self.encoder.encode(member_data))
        # the update never overwrites any value from data,
        # because an object can't have two attributes with the same name
        data.update(member_data)
        return data
Ejemplo n.º 40
0
    def month_picker_params(self) -> Optional[str]:
        """Returns the parameters for the month-picker, as a JSON text string.

        Returns:
            The parameters for the month-picker, as a JSON text string, or None
            if there is no data.
        """
        if self._data_start is None:
            return None
        start = datetime.date(self._data_start.year, self._data_start.month, 1)
        return DjangoJSONEncoder().encode({
            "locale": Language.current().locale,
            "minDate": start,
            "maxDate": self._data_end,
            "defaultDate": self.chosen_month(),
        })
Ejemplo n.º 41
0
def _render_app_html(request, initial_json):
    html = loader.render_to_string('app.html')
    ui_version = re.search('static/app-(.*)\.js', html).group(1)
    initial_json['meta'] = {
        'version': '{}-{}'.format(SEQR_VERSION, ui_version)
    }

    html = html.replace(
        "window.initialJSON=null", "window.initialJSON=" +
        json.dumps(initial_json, default=DjangoJSONEncoder().default))

    if request.get_host() == 'localhost:3000':
        html = re.sub(r'static/app(-.*)js', 'app.js', html)
        html = re.sub(r'<link\s+href="/static/app.*css"[^>]*>', '', html)

    return HttpResponse(html, content_type="text/html")
Ejemplo n.º 42
0
def pformat(value):
    """
    Better `pretty-print-format` using `DjangoJSONEncoder` with fallback to `pprint.pformat()`

    Try to use JSON fist, because it nicer than pprint.pformat() ;)
    Use DjangoJSONEncoder, because it can encode additional types like:
        date/time, decimal types, UUIDs
    """
    try:
        value = DjangoJSONEncoder(indent=4, sort_keys=True,
                                  ensure_ascii=False).encode(value)
    except TypeError:
        # Fallback if values are not serializable with JSON:
        value = pprint.pformat(value, width=120)

    return value
Ejemplo n.º 43
0
def render_component(path_to_source,
                     props=None,
                     to_static_markup=False,
                     json_encoder=None):
    if not os.path.isabs(path_to_source):
        path_to_source = finders.find(path_to_source) or path_to_source

    if json_encoder is None:
        json_encoder = DjangoJSONEncoder().encode

    html = render_core(path_to_source,
                       props,
                       to_static_markup,
                       json_encoder,
                       service_url=SERVICE_URL)

    return RenderedComponent(html, path_to_source, props, json_encoder)
Ejemplo n.º 44
0
 def save(self, old_record, list_record, detail_records):
     for record in detail_records:
         # Since parse_detail emits more than one record, we check for existing
         # records here rather than in self.existing_record()
         try:
             qs = NewsItem.objects.filter(
                 schema__id=self.schema.id,
                 item_date=record['inspection_date'])
             obj = qs.by_attribute(self.schema_fields['facility_id'],
                                   list_record['facid'])[0]
         except IndexError:
             pass
         else:
             return None
         if record['inspection_type'] == 'Consultation/Education - Field':
             continue
         inspection_type_lookup = self.get_or_create_lookup(
             'inspection_type',
             record['inspection_type'],
             record['inspection_type'],
             make_text_slug=False)
         violations_lookups = []
         for v in record['violations']:
             vl = self.get_or_create_lookup('violations',
                                            v['violation'],
                                            v['violation'],
                                            make_text_slug=False)
             violations_lookups.append(vl)
         attributes = {
             'name': list_record['name'],
             'inspection_type': inspection_type_lookup.id,
             'points': record['points'],
             'violations':
             ','.join([str(l.id) for l in violations_lookups]),
             'violations_json':
             DjangoJSONEncoder().encode(record['violations']),
             'facility_id': list_record['facid'],
         }
         self.create_newsitem(
             attributes,
             title=list_record['name'],
             url=
             'http://www.decadeonline.com/fac.phtml?agency=skc&forceresults=1&facid=%s'
             % list_record['facid'],
             item_date=record['inspection_date'],
             location_name=smart_title(list_record['location']))
Ejemplo n.º 45
0
    def default(self, obj):
        if isinstance(obj, recurly.resource.Money):
            return str(obj)

        # Resolve 'relatiator' attributes
        if callable(obj):
            result = obj()
            try:
                return result.to_dict(js=self.js)
            except:
                return result

        if isinstance(obj, recurly.Resource):
            return obj.to_dict(js=self.js)

        try:
            if issubclass(obj, dict) or issubclass(obj, list):
                return list(obj)
        except:
            pass

        return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 46
0
 def default(self, obj):
     if isinstance(obj, ObjectId):
         return str(obj)
     else:
         return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 47
0
 def default(self, obj):
     # to do not import pymongo it just compares class name
     if type(obj).__name__ == "ObjectId":
         return str(obj)
     else:
         return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 48
0
def json_response(response_obj):
    Encoder = DjangoJSONEncoder()
    return HttpResponse(Encoder.encode(response_obj))
Ejemplo n.º 49
0
 def default(self, obj):
     if (isinstance(obj, (date, list, dict, str, int, float, bool, type(None), Decimal)) or
             isinstance(obj, six.string_types)):
         return DjangoJSONEncoder.default(self, obj)
     return '{}'.format(type(obj).__name__)
Ejemplo n.º 50
0
 def default(self, obj):
     try:
         return DjangoJSONEncoder.default(self, obj)
     except TypeError:
         return obj.__dict__
Ejemplo n.º 51
0
def instance_to_json(instance, fields=None, exclude=None, indent=1):
    encoder = DjangoJSONEncoder(
        encoding='utf-8', ensure_ascii=False, sort_keys=False, indent=indent)
    return encoder.encode(instance_to_dict(instance, fields=fields, exclude=exclude))
Ejemplo n.º 52
0
 def default(self, obj):
     if isinstance(obj, Decimal):
         return float(obj)
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 53
0
def json_encode(data):
    encoder = DjangoJSONEncoder()
    return encoder.encode(data)
Ejemplo n.º 54
0
 def default(self, o, **kwargs):
   if isinstance(o, ObjectId):
     return str(o)
   else:
     return DjangoJSONEncoder.default(self, o, **kwargs)
Ejemplo n.º 55
0
def json_pack(feed):
	encoder=DjangoJSONEncoder()
	return HttpResponse(encoder.encode(feed))
Ejemplo n.º 56
0
 def default(self, obj):
     if isinstance(obj, QuerySet):
         return serializers.serialize("python", obj, ensure_ascii=False)
     return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 57
0
 def default(self, obj):
     if isinstance(obj, ApiModel):
         return obj.__dict__
     else:
         return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 58
0
 def default(self, o):
     if isinstance(o, datetime.datetime):
         o = make_local_time(o)
     return DjangoJSONEncoder.default(self, o)
Ejemplo n.º 59
0
    def default(self, obj):
        if isinstance(obj, timedelta):
            ARGS = ('days', 'seconds', 'microseconds')
            return {'__type__': 'datetime.timedelta',
                    'args': [getattr(obj, a) for a in ARGS]}
	return DjangoJSONEncoder.default(self, obj)
Ejemplo n.º 60
0
 def test_0_encode_default(self):
     djangoencoder = DjangoJSONEncoder()
     self.assertEquals(self.encoder.encode('str'), djangoencoder.encode('str'))