Python django.core.serializers.json.DjangoJSONEncoder() Examples

The following are code examples for showing how to use django.core.serializers.json.DjangoJSONEncoder(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cosinnus-core   Author: wechange-eg   File: http.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, data, status=200, content_type='application/json',
            **kwargs):
        """
        Create a new HTTP response which content_type defaults to
        ``'application/json'``.

        :param data: Any data type the
            :class:`~django.core.serializers.json.DjangoJSONEncoder` can
            handle (unless a different class is defined).
        :param int status: The HTTP response code. (Defaults to 200)
        :param str content_type: The content type for the response. (Defaults
            to ``'application/json'``)
        :param kwargs: Any additional kwargs are passed to the ``json.dumps``
            call.
        """
        ekwargs = {}
        ekwargs.update(DUMPS_KWARGS)
        dump = json.dumps(data, **ekwargs)
        super(JSONResponse, self).__init__(
            content=dump, status=status, content_type=content_type
        ) 
Example 2
Project: sw-django-utils   Author: telminov   File: json_utils.py    MIT License 6 votes vote down vote up
def qs_to_json(qs, fields=None):
    """
    transform QuerySet to json
    """
    if not fields :
        fields = [f.name for f in qs.model._meta.fields]


    # сформируем список для сериализации
    objects = []
    for value_dict in qs.values(*fields):
        # сохраним порядок полей, как определено в моделе
        o = OrderedDict()
        for f in fields:
            o[f] = value_dict[f]
        objects.append(o)

    # сериализуем
    json_qs = json.dumps(objects, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)
    return json_qs 
Example 3
Project: saleor-demo   Author: vubon   File: email.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_order_confirmation_markup(order):
    """Generates schema.org markup for order confirmation e-mail message."""
    organization = get_organization()
    order_url = build_absolute_uri(order.get_absolute_url())
    data = {
        '@context': 'http://schema.org',
        '@type': 'Order',
        'merchant': organization,
        'orderNumber': order.pk,
        'priceCurrency': order.total.gross.currency,
        'price': order.total.gross.amount,
        'acceptedOffer': [],
        'url': order_url,
        'potentialAction': {
            '@type': 'ViewAction',
            'url': order_url
        },
        'orderStatus': 'http://schema.org/OrderProcessing',
        'orderDate': order.created}

    lines = order.lines.prefetch_related('variant')
    for line in lines:
        product_data = get_product_data(line=line, organization=organization)
        data['acceptedOffer'].append(product_data)
    return json.dumps(data, cls=DjangoJSONEncoder) 
Example 4
Project: evm   Author: gdgnewdelhi   File: utils.py    MIT License 6 votes vote down vote up
def serialize_instance(instance):
    """
    Since Django 1.6 items added to the session are no longer pickled,
    but JSON encoded by default. We are storing partially complete models
    in the session (user, account, token, ...). We cannot use standard
    Django serialization, as these are models are not "complete" yet.
    Serialization will start complaining about missing relations et al.
    """
    data = {}
    for k, v in instance.__dict__.items():
        if k.startswith('_') or callable(v):
            continue
        try:
            if isinstance(instance._meta.get_field(k), BinaryField):
                v = force_text(base64.b64encode(v))
        except FieldDoesNotExist:
            pass
        data[k] = v
    return json.loads(json.dumps(data, cls=DjangoJSONEncoder)) 
Example 5
Project: django-xero   Author: toyg   File: models.py    Apache License 2.0 6 votes vote down vote up
def start_flow(cls, acceptance_url, next_page=None):
        """
        Start authorization flow
        """
        # instantiating credentials automatically starts the flow
        creds = PublicCredentials(get_xero_consumer_key(),
                                  get_xero_consumer_secret(),
                                  acceptance_url)
        # save state for later
        af_state = cls(state=json.dumps(creds.state,
                                        cls=DjangoJSONEncoder),
                       oauth_token=creds.oauth_token,
                       next_page=next_page)
        af_state.auth_url = creds.url
        af_state.save()
        return af_state 
Example 6
Project: django-xero   Author: toyg   File: models.py    Apache License 2.0 6 votes vote down vote up
def from_state(cls, creds: PublicCredentials, user):
        """ given a token reference, retrieve or construct a XeroUser instance.
        Note that you must already have a Django user, since Xero won't tell you
        anything about the logged-on user.
        :param creds: PublicCredentials instance with a valid session
        :param user: User instance
        :returns: XeroUser instance
        """
        if not creds.verified:
            raise Exception("Trying to create a XeroUser with "
                            "an invalid session")

        xero_user, created = cls.objects.get_or_create(
            user=user
        )
        xero_user.last_token = json.dumps(creds.state, cls=DjangoJSONEncoder)
        xero_user.save()
        return xero_user 
Example 7
Project: conference-web   Author: WebCampZg   File: import_tickets_xls.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle(self, *args, **options):
        event_id = options.get('event_id')
        source_file = options.get('source_file')

        event = Event.objects.get(pk=event_id)
        parse_fn_name = "parse_row_%s" % event.begin_date.year
        parse_fn = getattr(self, parse_fn_name)

        tickets = self.parse_xls(source_file, event_id, parse_fn)

        fixture = [{
            "model": "events.Ticket",
            "pk": None,
            "fields": ticket
        } for ticket in tickets]

        print(json.dumps(fixture, cls=DjangoJSONEncoder, indent=4)) 
Example 8
Project: cornerwise   Author: codeforboston   File: request.py    MIT License 6 votes vote down vote up
def make_message(request, data):
    extra_tags = None
    if isinstance(data, str):
        message = data
        level = messages.SUCCESS
    elif isinstance(data, dict):
        level = data.get("level", "success")
        level = getattr(messages, level.upper())
        message = json.dumps(data, cls=DjangoJSONEncoder)
        extra_tags = "json"
    elif isinstance(data, tuple):
        (message, level) = data

    if isinstance(level, str):
        level = getattr(messages, level.upper())

    messages.add_message(request, level, message, extra_tags=extra_tags) 
Example 9
Project: CATEd   Author: OnGridSystems   File: views.py    MIT License 6 votes vote down vote up
def get_holding(request):
    type_r = request.GET.get('type')
    if request.is_ajax():
        if type_r == 'names':
            names = []
            user_hold_names = UserHoldings.objects.values('type').distinct()
            if len(user_hold_names) > 0:
                for name in user_hold_names:
                    names.append(name['type'])
                return HttpResponse(json.dumps(names), status=200)
            else:
                return HttpResponse('none', status=200)
        else:
            holdings = UserHoldings.objects.filter(type=type_r).order_by('date_time')
            list_hold = [obj.as_list() for obj in holdings]
            return HttpResponse(json.dumps(list_hold, cls=DjangoJSONEncoder), status=200) 
Example 10
Project: agir.lafranceinsoumise.fr   Author: lafranceinsoumise   File: forms.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self):
        assets = {
            "js": [self.absolute_path(path) for path in self._js],
            "css": [
                [self.absolute_path(path), medium]
                for medium in self._css
                for path in self._css[medium]
            ],
        }

        json_assets = mark_safe(
            json.dumps(assets, cls=DjangoJSONEncoder).translate(_json_script_escapes)
        )

        return loader.get_template("lib/media_in_head.html").render(
            {"assets": json_assets}
        ) 
Example 11
Project: weibo-analysis-system   Author: Superbsco   File: views.py    MIT License 6 votes vote down vote up
def getLasted(request):
        infos = UserInfo.objects.values("_id", "Image" , "nick_name").order_by('crawl_time')
        user = json.dumps(list(infos), cls=DjangoJSONEncoder)
        targets = Target.objects.values("uid", "group")
        target = json.dumps(list(targets), cls=DjangoJSONEncoder)
        c=Counter()
        for word in targets:
            print(word['group'])
            c[word['group']] += 1
        li = list(c.items())
        li.sort(key=lambda x:x[0])
        result = {
            'user': user,
            'target': target,
            'count': json.dumps(li)
        }
        print(result)
        return JsonResponse(result, safe=False) 
Example 12
Project: araplus   Author: sparcs-kaist   File: views.py    MIT License 6 votes vote down vote up
def refresh_comment(request, grill_id):
    grill = get_object_or_404(Grill, pk=grill_id)
    # Update Comments
    new_index = request.POST['required_index']
    if not new_index:
        new_index = 1
    comments = GrillComment.objects.filter(
        grill=grill, order__gte=new_index)
    json_comments = map(lambda x: x.to_json(), list(comments))
    data = {'comments': json_comments}

    # Update Votes
    last_update = request.POST['last_update']
    votes = GrillCommentVote.objects.filter(
        grill_comment__grill=grill,
        created_time__gte=last_update
    ).values('grill_comment')
    last_update = datetime.datetime.now()
    votes = votes.annotate(new_count=Count('is_up'))
    # XXX: 어떻게 grill_comment가 알아서 order가 되지?
    # now, elem of votes : {'grill_comment', 'new_count'}
    data['new_votes'] = list(votes)
    data['last_update'] = last_update
    return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder),
                        content_type="application/json") 
Example 13
Project: payroll   Author: andela-sjames   File: views.py    MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):

        # cache this view for 1 hour
        cache_key = request.build_absolute_uri().split("?")[0]
        serialized_q = cache.get(cache_key)

        if not serialized_q:

            # query the DB for the report by id
            report_id = self.kwargs.get('report_id')
            try:
                report = Report.objects.get(report_id=report_id)
            except Report.DoesNotExist:
                return JsonResponse({
                    "msg": f"No Payroll report with id {report_id}",
                    "status": "failure",
                })

            queryset = report.payroll.values(
                'employee_id', 'pay_period', 'amount'
            )
            queryset = self.normalize_payroll(queryset)
            serialized_q = json.dumps(list(queryset), cls=DjangoJSONEncoder)

        cache.set(cache_key, serialized_q)

        # return payroll at this point.
        return JsonResponse({
            "msg": "payroll loading",
            "status": "success",
            "data": serialized_q
        }) 
Example 14
Project: payroll   Author: andela-sjames   File: views.py    MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):

        # cache is set to cache for 1 hour
        # from the settings file.
        cache_key = request.build_absolute_uri().split("?")[0]
        serialized_q = cache.get(cache_key)

        if not serialized_q:

            # query the DB for the report by id
            report_id = self.kwargs.get('report_id')
            try:
                report = Report.objects.get(report_id=report_id)
            except Report.DoesNotExist:
                return JsonResponse({
                    "msg": f"No Pay report with id {report_id}",
                    "status": "failure",
                })

            queryset = report.pay.values(
                'date', 'hours', 'employee_id', 'job_group'
            )
            queryset = self.normalize_report(queryset)
            serialized_q = json.dumps(list(queryset), cls=DjangoJSONEncoder)

        cache.set(cache_key, serialized_q)

        # return result at this point.
        return JsonResponse({
            "msg": "report loading",
            "status": "success",
            "data": serialized_q
        }) 
Example 15
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def json_validate_rfc(request, rfc):
    url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(rfc)
    results = create_output(url)
    results = json.dumps(results, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 16
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def json_validate_draft(request, draft):
    url = 'http://tools.ietf.org/id/{!s}'.format(draft)
    results = create_output(url)
    results = json.dumps(results, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 17
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datatracker_rfc(request):
    documents = []
    rfcs = request.GET.getlist('doc')
    for doc in rfcs:
        url = 'https://tools.ietf.org/rfc/rfc{!s}.txt'.format(doc)
        results = create_output(url, for_datatracker=True)
        results["name"] = doc
        documents.append(results)
    result = {"yangvalidator-version": versions['validator_version'],
              "documents": documents}
    results = json.dumps(result, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 18
Project: bottle-yang-extractor-validator   Author: YangCatalog   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def datatracker_draft(request):
    documents = []
    drafts = request.GET.getlist('doc')
    for doc in drafts:
        url = 'http://tools.ietf.org/id/{!s}'.format(doc)
        results = create_output(url, for_datatracker=True)
        results["name"] = doc
        documents.append(results)
    result = {"yangvalidator-version": versions['validator_version'],
              "documents": documents}
    results = json.dumps(result, cls=DjangoJSONEncoder)
    return HttpResponse(results, content_type='application/json') 
Example 19
Project: Servo   Author: fpsw   File: utils.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dumps(self, obj):
        return json.dumps(obj, cls=DjangoJSONEncoder) 
Example 20
Project: Servo   Author: fpsw   File: utils.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def loads(self, data):
        return json.loads(data, cls=DjangoJSONEncoder) 
Example 21
Project: ThingCloud   Author: nick6918   File: utils.py    MIT License 5 votes vote down vote up
def __init__(self,content='',*arg, **kw):
		super(Jsonify, self).__init__(content,*arg, **kw)
		self.content = json.dumps(content,indent=4,sort_keys=True,cls=DjangoJSONEncoder,ensure_ascii=False)
		self['Content-Type']='application/json; charset=utf-8'
		self['Vary']= 'Accept-Encoding'
		self['Content-Length'] = len(self.content) 
Example 22
Project: figures   Author: appsembler   File: logger.py    MIT License 5 votes vote down vote up
def log_error(error_data, error_type=None, **kwargs):
    kwargs.get('logger', default_logger).error(json.dumps(
        error_data,
        sort_keys=True,
        indent=1,
        cls=DjangoJSONEncoder))

    if figure_helpers.log_pipeline_errors_to_db() or kwargs.get('log_pipeline_errors_to_db', False):
        log_error_to_db(error_data, error_type, **kwargs) 
Example 23
Project: django-pusherable   Author: pusher   File: mixins.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __object_to_json_serializable(self, object):
        model_dict = model_to_dict(object,
                                   fields=self.pusher_include_model_fields, exclude=self.pusher_exclude_model_fields)
        json_data = json.dumps(model_dict, cls=DjangoJSONEncoder)
        data = json.loads(json_data)
        return data 
Example 24
Project: djing   Author: nerosketch   File: migrate2v2_dump.py    The Unlicense 5 votes vote down vote up
def batch_save(fname, *args, **kwargs):
    sa = BatchSaveStreamList(*args, **kwargs)
    print(fname)
    with open(fname, 'w') as f:
        dump(sa, f, ensure_ascii=False, indent=2, cls=DjangoJSONEncoder)


# --------------------- 
Example 25
Project: chattR   Author: patrickstocklin   File: response.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 26
Project: universal_notifications   Author: HealthByRo   File: fields.py    MIT License 5 votes vote down vote up
def dumps(value):
    return DjangoJSONEncoder().encode(value) 
Example 27
Project: django-multiple-file-chunked-upload   Author: tcztzy   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, content, status=200, *args, **kwargs):
        super(UploadResponse, self).__init__(
            content=DjangoJSONEncoder().encode(content),
            content_type='application/json',
            status=status,
            *args, **kwargs
        ) 
Example 28
Project: longclaw   Author: JamesRamm   File: processors.py    MIT License 5 votes vote down vote up
def get_rates_cache_key(self, **kwargs):
        from longclaw.basket.serializers import BasketItemSerializer
        
        settings = kwargs['settings']
        origin = settings.shipping_origin
        destination = kwargs['destination']
        basket_id = kwargs['basket_id']
        
        items = BasketItem.objects.filter(basket_id=basket_id)
        serialized_items = BasketItemSerializer(items, many=True)
        
        serialized_origin = AddressSerializer(origin) or None
        serialized_destination = AddressSerializer(destination) or None
        
        data = {
            "items": serialized_items.data,
            "origin": serialized_origin.data,
            "destination": serialized_destination.data,
        }
        
        raw_key = json.dumps(
            data,
            sort_keys=True,
            indent=4,
            separators=(',', ': '),
            cls=DjangoJSONEncoder,
        )
        
        hashed_key = hashlib.sha1(force_bytes(raw_key)).hexdigest()
        
        return force_text(hashed_key) 
Example 29
Project: AneMo   Author: jspargo   File: response.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 30
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def json(data):
    """
    Safely JSON-encode an object.

    To protect against XSS attacks, HTML special characters (<, >, &) and unicode newlines
    are replaced by escaped unicode characters. Django does not escape these characters
    by default.

    Output of this method is not marked as HTML safe. If you use it inside an HTML
    attribute, it must be escaped like regular data:

    <div data-user="{{ data|json }}">

    If you use it inside a <script> tag, then the output does not need to be escaped,
    so you can mark it as safe:

    <script>
    var user = {{ data|json|safe }};
    </script>

    Escaped characters taken from Rails json_escape() helper:
    https://github.com/rails/rails/blob/v4.2.5/activesupport/lib/active_support/core_ext/string/output_safety.rb#L60-L113
    """
    unsafe_chars = {
        '&': '\\u0026',
        '<': '\\u003c',
        '>': '\\u003e',
        '\u2028': '\\u2028',
        '\u2029': '\\u2029'}
    json_str = json_dumps(data, cls=DjangoJSONEncoder)

    for (c, d) in unsafe_chars.items():
        json_str = json_str.replace(c, d)

    return json_str 
Example 31
Project: GTDWeb   Author: lanbing510   File: response.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 32
Project: liberator   Author: libscie   File: response.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 33
Project: otreeutils   Author: WZBSocialScienceCenter   File: scripts.py    Apache License 2.0 5 votes vote down vote up
def save_data_as_json_file(data, path, **kwargs):
    from django.core.serializers.json import DjangoJSONEncoder

    with open(path, 'w') as f:
        json.dump(data, f, cls=DjangoJSONEncoder, **kwargs) 
Example 34
Project: sw-django-utils   Author: telminov   File: json_utils.py    MIT License 5 votes vote down vote up
def object_to_json(obj, indent=2):
    """
        transform object to json
    """
    instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder)
    return instance_json 
Example 35
Project: sw-django-utils   Author: telminov   File: json_utils.py    MIT License 5 votes vote down vote up
def mongoqs_to_json(qs, fields=None):
    """
    transform mongoengine.QuerySet to json
    """

    l = list(qs.as_pymongo())

    for element in l:
        element.pop('_cls')

    # use DjangoJSONEncoder for transform date data type to datetime
    json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)
    return json_qs 
Example 36
Project: django-celery-tracker   Author: chris-allen   File: views.py    MIT License 5 votes vote down vote up
def task_details(request, task_id):
    task = get_object_or_404(CeleryTask, task_id=task_id)
    res = AsyncResult(task_id)

    details = {
        'task_name': task.task_name,
        'task_id': task_id,
        'args': task.args,
        'created': task.created,
        'started': task.started,
        'completed': task.completed,
    }

    try:
        details['state'] = res.state
        if res.traceback is not None:
            details['traceback'] = str(res.traceback).replace('\n', '<br/>')
    except TypeError:
        # Celery doesn't have a record of this uuid
        details['state'] = 'UNKNOWN'

    if task.post_state:
        details['state'] = task.post_state

    return HttpResponse(
        json.dumps(details, cls=DjangoJSONEncoder),
        content_type='application/json',
    ) 
Example 37
Project: banruo   Author: yingshang   File: html.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def json_script(value, element_id):
    """
    Escape all the HTML/XML special characters with their unicode escapes, so
    value is safe to be output anywhere except for inside a tag attribute. Wrap
    the escaped JSON in a script tag.
    """
    from django.core.serializers.json import DjangoJSONEncoder
    json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)
    return format_html(
        '<script id="{}" type="application/json">{}</script>',
        element_id, mark_safe(json_str)
    ) 
Example 38
Project: banruo   Author: yingshang   File: response.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super().__init__(content=data, **kwargs) 
Example 39
Project: banruo   Author: yingshang   File: client.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
        self.json_encoder = json_encoder
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO() 
Example 40
Project: kobo-predict   Author: awemulya   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, pk, **kwargs):
        schedule = FieldSightXF.objects.filter(site_id=pk, is_scheduled = True, is_staged=False, is_survey=False).values('id','xf__title','date_created')
        stage = FieldSightXF.objects.filter(site_id=pk, is_scheduled = False, is_staged=True, is_survey=False).values('id','xf__title','date_created')
        survey = FieldSightXF.objects.filter(site_id=pk, is_scheduled = False, is_staged=False, is_survey=True).values('id','xf__title','date_created')
        general = FieldSightXF.objects.filter(site_id=pk, is_scheduled = False, is_staged=False, is_survey=False).values('id','xf__title','date_created')
        content={'general':list(general), 'schedule':list(schedule), 'stage':list(stage), 'survey':list(survey)}
        return JsonResponse(json.dumps(content, cls=DjangoJSONEncoder, ensure_ascii=False).encode('utf8'), status=200) 
Example 41
Project: kobo-predict   Author: awemulya   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, pk, **kwargs):
        coord_datas = get_site_responses_coords(pk)
        obj = Site.objects.get(pk=self.kwargs.get('pk'))
        response_coords = list(coord_datas["result"])
        response_coords.append({'geometry': {'coordinates': [obj.latitude, obj.longitude], 'type': 'Point'},
                                              'properties': {'fs_uuid': 'None',
                                              'id':'#' ,
                                              'submitted_by': 'site_origin'},
                                              'type': 'Feature'})
        return render(request, 'fieldsight/site_response_map_view.html', {
            'co_ords': json.dumps(response_coords, cls=DjangoJSONEncoder, ensure_ascii=False).encode('utf8'),
            'geo_layers': obj.project.geo_layers.all(),
            'is_donor_only' : kwargs.get('is_donor_only', False)
        }) 
Example 42
Project: kobo-predict   Author: awemulya   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post(self, request, pk):
        coord_datas = get_site_responses_coords(pk)
        content={'coords-data':list(coord_datas["result"])}
        return JsonResponse(json.dumps(content, cls=DjangoJSONEncoder, ensure_ascii=False).encode('utf8'), status=200) 
Example 43
Project: kobo-predict   Author: awemulya   File: views.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, pk, **kwargs):
        all_imgs = get_images_for_site_all(pk)
        return render(request, 'fieldsight/gallery.html', {'is_donor_only': kwargs.get('is_donor_only', False), 'all_imgs' : json.dumps(list(all_imgs["result"]), cls=DjangoJSONEncoder, ensure_ascii=False).encode('utf8')}) 
Example 44
Project: media-webapp   Author: uisautomation   File: to_json.py    MIT License 5 votes vote down vote up
def to_json(value):
    """
    Encode a value to JSON using the DjangoJSONEncoder. Escape all the HTML/XML special characters
    with their unicode escapes, so value is safe to be output anywhere except for inside a tag
    attribute.

    See: https://docs.djangoproject.com/en/2.1/topics/serialization/#serialization-formats-json
    See: django.utils.html.json_script

    """
    json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)
    return format_html('{}', mark_safe(json_str)) 
Example 45
Project: Fun5G   Author: OpenWinCon   File: response.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 46
Project: xnova.py   Author: xnova   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def player_detail(request, player_id):
    encoder = DjangoJSONEncoder()

    user = User.objects.get(pk=player_id)
    data = {
        'attributes': {'name': user.username, 'email': user.email},
        'relationships': {'homeplanet': None}
    }
    return HttpResponse(encoder.encode({'data': data}),
                        content_type='application/vnd.api+json') 
Example 47
Project: blockcypher-explorer   Author: linuxmahara   File: views.py    Apache License 2.0 5 votes vote down vote up
def poll_confidence(request, coin_symbol, tx_hash):
    transaction_details = get_transaction_details(
            tx_hash=tx_hash,
            coin_symbol=coin_symbol,
            limit=1,
            api_key=BLOCKCYPHER_API_KEY,
            )

    #import pprint; pprint.pprint(transaction_details, width=1)

    confidence = transaction_details.get('confidence')
    if confidence:
        confidence_pct = min(round(confidence * 100, 2), 99.99)
    else:
        confidence_pct = None

    json_dict = {
            'confidence': confidence,
            'confidence_pct': confidence_pct,
            'confidence_pct_scaled': scale_confidence(confidence),
            'double_spend_detected': transaction_details['double_spend'],
            'receive_cnt': transaction_details.get('receive_count'),
            }

    json_response = json.dumps(json_dict, cls=DjangoJSONEncoder)

    return HttpResponse(json_response, content_type='application/json') 
Example 48
Project: django-abnorm   Author: trashnroll   File: utils.py    MIT License 5 votes vote down vote up
def dumps(value):
    return DjangoJSONEncoder().encode(value) 
Example 49
Project: Vigtech-Services   Author: VigTech   File: response.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 50
Project: labs-striker   Author: wikimedia   File: toolinfo.py    GNU General Public License v3.0 5 votes vote down vote up
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"
    ) 
Example 51
Project: DroidPot   Author: WhySoGeeky   File: response.py    MIT License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 52
Project: PopularityBased-SearchEngine   Author: rsunder10   File: response.py    MIT License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 53
Project: news_proj   Author: TheoElia   File: html.py    MIT License 5 votes vote down vote up
def json_script(value, element_id):
    """
    Escape all the HTML/XML special characters with their unicode escapes, so
    value is safe to be output anywhere except for inside a tag attribute. Wrap
    the escaped JSON in a script tag.
    """
    from django.core.serializers.json import DjangoJSONEncoder
    json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)
    return format_html(
        '<script id="{}" type="application/json">{}</script>',
        element_id, mark_safe(json_str)
    ) 
Example 54
Project: news_proj   Author: TheoElia   File: response.py    MIT License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super().__init__(content=data, **kwargs) 
Example 55
Project: news_proj   Author: TheoElia   File: client.py    MIT License 5 votes vote down vote up
def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
        self.json_encoder = json_encoder
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO() 
Example 56
Project: mudong_blog   Author: mudong1991   File: response.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 57
Project: wagtail-import-export-tool   Author: berkalpyakici   File: exporting.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def instance_to_data(instance, null_users=False):
    """
    A utility to create JSON-able data from a model instance.

    Arguments:
    instance -- objects.get() object instance.
    null_users -- Whether to null user references.
    
    Returns:
    A dictionary of metadata of instance.
    """

    data = {}

    for key, value in instance.__dict__.items():
        if isinstance(value, ModelState):
            continue
        elif null_users == True and ('user_id' in key or 'owner' in key):
            data[key] = None
        elif isinstance(value, StreamValue):
            data[key] = json.dumps(value.stream_data, cls=DjangoJSONEncoder)
        elif isinstance(value, FieldFile) or isinstance(value, File):
            data[key] = {'name': value.name, 'size': value.size}
        else:
            data[key] = value
    return data 
Example 58
Project: Bookmark   Author: AnkurRyder   File: response.py    MIT License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 59
Project: EvenniaPluginSampleProject   Author: castlelorestudios   File: response.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 60
Project: django-admino   Author: erdem   File: sites.py    MIT License 5 votes vote down vote up
def api_detail(self, request, *args, **kwargs):
        obj = self.get_object(request, object_id=kwargs.get("pk"))
        ModelForm = self.get_form(request, obj=obj)
        form = ModelForm(instance=obj)
        data = self.obj_as_dict(request, form.instance)
        return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type='application/json') 
Example 61
Project: django-admino   Author: erdem   File: sites.py    MIT License 5 votes vote down vote up
def api_create(self, request, *args, **kwargs):
        data = json.loads(request.body)

        ModelForm = self.get_form(request, obj=None)
        form = ModelForm(data=data, files=request.FILES)
        if form.is_valid():
            obj = form.save()
            data = self.obj_as_dict(request, obj)
            return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json")
        else:
            errors = {
                "errors": json.loads(form.errors.as_json())
            }
            return HttpResponse(json.dumps(errors), status=400, content_type="application/json") 
Example 62
Project: vue-django-element-django   Author: jonathanmusto   File: response.py    MIT License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super().__init__(content=data, **kwargs) 
Example 63
Project: adhocracy-plus   Author: liqd   File: models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def process_form_submission(self, form):
        data = form.cleaned_data
        submission = self.get_submission_class().objects.create(
            form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),
            page=self, email=data['email'], message=data['message'],
            telephone_number=data['telephone_number'], name=data['name']
        )
        if self.to_address:
            self.send_mail(form)
        if form.cleaned_data['receive_copy']:
            AnswerToContactFormEmail.send(submission)
        return submission 
Example 64
Project: encarnia   Author: whitehorse-io   File: response.py    MIT License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs) 
Example 65
Project: cornerwise   Author: codeforboston   File: request.py    MIT License 5 votes vote down vote up
def json_view(view):
    def json_handler(req, *args, **kwargs):
        resp = HttpResponse(json.dumps(view(req, *args, **kwargs),
                                       cls=DjangoJSONEncoder))
        resp["Content-type"] = "application/json"
        return resp

    return json_handler 
Example 66
Project: weibo-analysis-system   Author: Superbsco   File: views.py    MIT License 5 votes vote down vote up
def getQuick(request):
        infos = UserInfo.objects.values("_id", "Image" ,"NickName")
        result = json.dumps(list(infos), cls=DjangoJSONEncoder)
        print(result)
        return JsonResponse(result, safe=False) 
Example 67
Project: weibo-analysis-system   Author: Superbsco   File: views.py    MIT License 5 votes vote down vote up
def getWeibo(request):
        infos = CommentWeiboInfo.objects.values("wb_id", "wb_userId", "wb_userName" ,"wb_user_profile_image_url", "wb_text")
        result = json.dumps(list(infos), cls=DjangoJSONEncoder)
        print(result)
        return JsonResponse(result, safe=False)

#日期转化代码 
Example 68
Project: komposto.org   Author: fatiherikli   File: models.py    MIT License 5 votes vote down vote up
def as_json(self):
        return json.dumps(self.serialize(), cls=DjangoJSONEncoder) 
Example 69
Project: xr-web   Author: xr-web-de   File: models.py    MIT License 5 votes vote down vote up
def process_form_submission(self, form):
        submission = self.get_submission_class()(
            form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder), page=self
        )
        if self.save_submission:
            submission.save()
        if self.to_address:
            self.send_mail(form)
        return submission 
Example 70
Project: letsmeet.click   Author: letsmeet-click   File: feeds.py    MIT License 5 votes vote down vote up
def write(self, outfile, encoding):
        data = {}
        data.update(self.feed)
        data['items'] = self.items
        json.dump(data, outfile, cls=DjangoJSONEncoder)
        # outfile is a HttpResponse
        if isinstance(outfile, HttpResponse):
            outfile['Access-Control-Allow-Origin'] = '*' 
Example 71
Project: Python-Programming-Blueprints   Author: PacktPublishing   File: views.py    MIT License 5 votes vote down vote up
def _prepare_order_data(cart):

    cart_items = ShoppingCartItem.objects.values_list(
        'game__name',
        'price_per_unit',
        'game__id',
        'quantity').filter(cart__id=cart.id)

    order = cart_items.aggregate(
        total_order=Sum(F('price_per_unit') * F('quantity'),
                        output_field=DecimalField(decimal_places=2))
    )

    order_items = [OrderItem(*x)._asdict() for x in cart_items]

    order_customer = {
        'customer_id': cart.user.id,
        'email': cart.user.email,
        'name': f'{cart.user.first_name} {cart.user.last_name}'
    }

    order_dict = {
        'items': order_items,
        'order_customer': order_customer,
        'total': order['total_order']
    }

    return json.dumps(order_dict, cls=DjangoJSONEncoder) 
Example 72
Project: araplus   Author: sparcs-kaist   File: views.py    MIT License 5 votes vote down vote up
def add_comment(request, grill_id):
    post_data = request.POST
    grill = get_object_or_404(Grill, pk=grill_id)
    userprofile = UserProfile.objects.get(user=request.user)
    new_comment = GrillComment(
        grill=grill, author=userprofile, content=post_data.get('new_content'))
    new_comment.save()
    new_comment.grill.updated_time = datetime.datetime.now()
    new_comment.grill.save()

    ms = '<li id="comment-' + str(new_comment.order) +\
         '" class="list-group-item">'
    ms += '<div>'
    ms += '<div class="comment-meta">'
    ms += '<span class="col-md-1">' + str(new_comment.order) + '</span>'
    ms += '<strong>' + new_comment.author.nickname.encode('utf-8')
    ms += '</strong>'
    ms += '<span class="pull-right">' + str(new_comment.created_time)
    ms += '</span></div>'
    ms += '<div class="comment-content-container">'
    ms += '<span>' + new_comment.replace_tags().encode('utf8') + '</span>'
    ms += '<div class="comment-vote-container">'
    ms += '<button class="vote-up btn btn-default"> 추천 (+0) </button>'
    ms += '<button class="vote-down btn btn-default"> 반대 (-0)</button>'
    ms += '</div></div></div></li>'
    data = {'html': ms}
    return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder),
                        content_type="application/json") 
Example 73
Project: eperpus   Author: HilmiZul   File: html.py    MIT License 5 votes vote down vote up
def json_script(value, element_id):
    """
    Escape all the HTML/XML special characters with their unicode escapes, so
    value is safe to be output anywhere except for inside a tag attribute. Wrap
    the escaped JSON in a script tag.
    """
    from django.core.serializers.json import DjangoJSONEncoder
    json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes)
    return format_html(
        '<script id="{}" type="application/json">{}</script>',
        element_id, mark_safe(json_str)
    ) 
Example 74
Project: eperpus   Author: HilmiZul   File: response.py    MIT License 5 votes vote down vote up
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super().__init__(content=data, **kwargs) 
Example 75
Project: eperpus   Author: HilmiZul   File: client.py    MIT License 5 votes vote down vote up
def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
        self.json_encoder = json_encoder
        self.defaults = defaults
        self.cookies = SimpleCookie()
        self.errors = BytesIO() 
Example 76
Project: aashe-auth   Author: AASHE   File: models.py    MIT License 5 votes vote down vote up
def set_drupal_user_dict(self, user_dict):
        """
            Converts the drupal user dictionary to a string and stores it
            on the model.
        """
        if isinstance(user_dict, dict):
            self.drupal_user_dict = json.dumps(user_dict,
                                               cls=DjangoJSONEncoder)
        else:
            self.drupal_user_dict = "" 
Example 77
Project: data-workspace   Author: uktrade   File: views.py    MIT License 4 votes vote down vote up
def get(self, request, *args, **kwargs):
        dl_format = self.kwargs.get('format')
        if dl_format not in ['json', 'csv']:
            raise Http404
        ref_dataset = self.get_object()
        records = []
        for record in ref_dataset.get_records():
            record_data = {}
            for field in ref_dataset.fields.all():
                field_name = field.name
                value = getattr(record, field.column_name)
                # If this is a linked field display the display name and id of that linked record
                if field.data_type == ReferenceDatasetField.DATA_TYPE_FOREIGN_KEY:
                    record_data[get_linked_field_identifier_name(field)] = (
                        value.get_identifier() if value is not None else None
                    )
                    record_data[get_linked_field_display_name(field)] = (
                        value.get_display_name() if value is not None else None
                    )
                else:
                    record_data[field_name] = value
            records.append(record_data)

        response = HttpResponse()
        response['Content-Disposition'] = 'attachment; filename={}-{}.{}'.format(
            ref_dataset.slug, ref_dataset.published_version, dl_format
        )

        log_event(
            request.user,
            EventLog.TYPE_REFERENCE_DATASET_DOWNLOAD,
            ref_dataset,
            extra={
                'path': request.get_full_path(),
                'reference_dataset_version': ref_dataset.published_version,
                'download_format': dl_format,
            },
        )
        ref_dataset.number_of_downloads = F('number_of_downloads') + 1
        ref_dataset.save(update_fields=['number_of_downloads'])

        if dl_format == 'json':
            response['Content-Type'] = 'application/json'
            response.write(json.dumps(list(records), cls=DjangoJSONEncoder))
        else:
            response['Content-Type'] = 'text/csv'
            with closing(io.StringIO()) as outfile:
                writer = csv.DictWriter(
                    outfile,
                    fieldnames=ref_dataset.export_field_names,
                    quoting=csv.QUOTE_NONNUMERIC,
                )
                writer.writeheader()
                writer.writerows(records)
                response.write(outfile.getvalue())  # pylint: disable=no-member
        return response 
Example 78
Project: xnova.py   Author: xnova   File: views.py    GNU General Public License v3.0 4 votes vote down vote up
def player_list(request):
    """
    :type request: rest_framework.
    :rtype: HttpResponse
    """
    encoder = DjangoJSONEncoder()

    if request.method == 'POST':
        content = json.loads(request.body)
        attributes = content['data']['attributes']
        if User.objects.filter(email=attributes['email']).count():
            return HttpResponse(
                encoder.encode({'errors': [{
                    'detail': 'A player with the same email already exists',
                    'source': {'pointer': '/data/attributes/email'}
                }]}),
                status=400,
                content_type='application/vnd.api+json')
        try:
            new_user = User.objects.create_user(
                attributes['name'],
                email=attributes['email'])
            return HttpResponse(
                encoder.encode({
                    'data': {
                        'type': 'users',
                        'id': new_user.id,
                        'attributes': {
                            'name': attributes['name'],
                            'email': attributes['email'],
                        },
                        'links': {
                            'self': '/players/%d/' % (new_user.id,)
                        }
                    }
                }),
                content_type='application/vnd.api+json')
        except Exception, e:
            return HttpResponse(
                encoder.encode({'errors': [{
                    'detail': 'A player with the same name already exists',
                    'source': {'pointer': '/data/attributes/name'}
                }]}),
                status=400,
                content_type='application/vnd.api+json'
            ) 
Example 79
Project: CATEd   Author: OnGridSystems   File: views.py    MIT License 4 votes vote down vote up
def get_ticker(request):
    if request.is_ajax():
        pair_id = request.POST.get('pair_id')
        intervale = int(request.POST.get('intervale'))
        zoom = request.POST.get('zoom')
        chart_data = {}
        ticker_list = []
        extremums_list = []
        intervales = []
        if zoom == 'all':
            ticker = list(ExchangeTicker.objects.values('date_time', 'last').filter(pair_id=pair_id))
        else:
            ticker = list(ExchangeTicker.objects.values('date_time', 'last').filter(pair_id=pair_id,
                                                                                    date_time__gte=timezone.now() - datetime.timedelta(
                                                                                        hours=int(zoom))))
        if len(ticker) > 0:
            extremums = Extremum.objects.filter(pair_id=pair_id,
                                                date__gte=ticker[0]['date_time'])
            for item in extremums:
                extremums_list.append([item.date, item.price, item.ext_type])
            s_date = ticker[0]['date_time']
            while s_date < timezone.now():
                intervales.append(s_date)
                s_date = s_date + datetime.timedelta(minutes=intervale)
            if len(intervales) > 0:
                s_date = intervales.pop(0)
                # print('От {} до {}'.format(s_date, s_date + datetime.timedelta(minutes=intervale)))
                s_chain = [x for x in ticker if
                           s_date + datetime.timedelta(minutes=intervale) > x['date_time'] >= s_date]
                while len(intervales) > 0:
                    try:
                        ticker_list.append({'date': s_date,
                                            'open': s_chain[0]['last'],
                                            'close': s_chain[-1]['last'],
                                            'low': min([x['last'] for x in s_chain]),
                                            'high': max([x['last'] for x in s_chain])})
                    except IndexError:
                        pass
                    s_date = intervales.pop(0)
                    # print('Новая от {} до {}'.format(s_date, s_date + datetime.timedelta(minutes=intervale)))
                    s_chain = [x for x in ticker if
                               s_date + datetime.timedelta(minutes=intervale) > x['date_time'] >= s_date]
                    # print("Выборка {}".format(s_chain))
        chart_data['ticker'] = ticker_list
        chart_data['extremums'] = extremums_list
        return HttpResponse(json.dumps(chart_data, cls=DjangoJSONEncoder), status=200) 
Example 80
Project: agir.lafranceinsoumise.fr   Author: lafranceinsoumise   File: extract_person.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def handle(self, *args, person_email, **options):
        try:
            p = Person.objects.get_by_natural_key(person_email)
        except Person.DoesNotExist:
            raise CommandError("L'email donné est inconnu.")

        spec_role = get_all_fields(Role)

        spec_event = {
            "Nom": "name",
            "URL": ("id", lambda id: front_url("view_event", args=[id])),
        }
        spec_membership = {
            "Nom": "supportgroup.name",
            "URL": ("supportgroup.id", lambda id: front_url("view_group", args=[id])),
            "Animateur": "is_referent",
            "Gestionnaire": "is_manager",
        }

        spec_payment = get_all_fields(Payment)
        spec_subscription = get_all_fields(Subscription)
        spec_event_images = get_all_fields(EventImage)
        spec_form_submissions = get_all_fields(PersonFormSubmission)
        spec_tags = get_all_fields(PersonTag)

        spec_person = {
            **get_all_fields(Person),
            "pays": ("location_country", str),
            "Rôle": ("role", spec_role),
            "événements organisés": ("organized_events", T.all(), [spec_event]),
            "participations aux événements": (
                "rsvps",
                T.all(),
                [("event", spec_event)],
            ),
            "participations à des groupes": ("memberships", T.all(), [spec_membership]),
            "paiements": ("payments", T.all(), [spec_payment]),
            "souscription au don mensuel": Coalesce(
                ("subscription", spec_subscription), default=None
            ),
            "images d'événements": ("event_images", T.all(), [spec_event_images]),
            "réponses à des formulaires": (
                "form_submissions",
                T.all(),
                [spec_form_submissions],
            ),
            "libellés": ("tags", T.all(), [spec_tags]),
        }

        self.stdout.ending = ""
        json.dump(glom(p, spec_person), self.stdout, cls=DjangoJSONEncoder)