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

The following are 30 code examples of django.core.serializers.json.DjangoJSONEncoder(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.serializers.json , or try the search function .
Example #1
Source File: test_jsonrpc_errors.py    From django-modern-rpc with MIT License 6 votes vote down vote up
def test_jsonrpc_invalid_request_3(all_rpc_url):

    # Bad value for payload member 'jsonrpc'

    headers = {'content-type': 'application/json'}
    payload = {
        "method": 'add',
        "params": [5, 6],
        "jsonrpc": "1.0",
        "id": random.randint(1, 1000),
    }
    req_data = json.dumps(payload, cls=DjangoJSONEncoder)
    response = requests.post(all_rpc_url, data=req_data, headers=headers).json()

    assert 'The attribute "jsonrpc" must contain "2.0"' in response['error']['message']
    assert RPC_INVALID_REQUEST == response['error']['code'] 
Example #2
Source File: views.py    From CATEd with 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 #3
Source File: json_filters.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def json_in_script_tag(serialized_data):
    """Convert serialized data to HTML <script>-safe JSON.

    Example usage:

        <script>
            window.foo = {{foo|json_serialized_data}}
        </script>

    To render, we:

        1. JSON-encode, using Django's default encoder (to encode
           datetime as string, for instance).
        2. Replace `<` with `\u003c`, to prevent injection of `</script>` in
           the JSON.
    """
    if not serialized_data:
        return mark_safe("null")

    raw = DjangoJSONEncoder().encode(serialized_data)
    escaped = escape_potential_hack_chars(raw)
    return mark_safe(escaped) 
Example #4
Source File: views.py    From weibo-analysis-system with 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 #5
Source File: json_writer.py    From tw-rental-house-data with MIT License 6 votes vote down vote up
def write(self, filename, row=None, last_line=False):
        if filename not in self.__files:
            fh = open('{}_{}.json'.format(self.__file_prefix, filename), 'w')
            self.__files[filename] = {
                'fh': fh,
                'last': row
            }
            fh.write('[\n')
        elif self.__files[filename]['last']:
            f = self.__files[filename]
            fh = f['fh']
            join_token = '' if last_line else ','
            json_str = json.dumps(
                f['last'],
                cls=DjangoJSONEncoder,
                ensure_ascii=False,
                sort_keys=True
            )
            fh.write('{}{}\n'.format(json_str, join_token))
            f['last'] = row 
Example #6
Source File: request.py    From cornerwise with 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 #7
Source File: json.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def _preencode(data, magic_marker, in_coords=False, in_groups=False):
    if isinstance(data, dict):
        data = data.copy()
        for name, value in tuple(data.items()):
            if name in ('bounds', 'point', 'locations') and isinstance(value, (tuple, list)):
                data[name] = magic_marker+json.dumps(value, cls=DjangoJSONEncoder)+magic_marker
            else:
                data[name] = _preencode(value, magic_marker,
                                        in_coords=(name == 'coordinates'), in_groups=(name == 'groups'))
        return data
    elif isinstance(data, (tuple, list)):
        if (in_coords and data and isinstance(data[0], (int, float))) or in_groups:
            return magic_marker+json.dumps(data, cls=DjangoJSONEncoder)+magic_marker
        else:
            return tuple(_preencode(value, magic_marker, in_coords) for value in data)
    else:
        return data 
Example #8
Source File: test_jsonrpc_errors.py    From django-modern-rpc with MIT License 6 votes vote down vote up
def test_jsonrpc_invalid_request_1(all_rpc_url):

    # Missing 'method' in payload

    headers = {'content-type': 'application/json'}
    payload = {
        # "method": 'add',
        "params": [5, 6],
        "jsonrpc": "2.0",
        "id": random.randint(1, 1000),
    }
    req_data = json.dumps(payload, cls=DjangoJSONEncoder)
    response = requests.post(all_rpc_url, data=req_data, headers=headers).json()

    assert 'Missing parameter "method"' in response['error']['message']
    assert RPC_INVALID_REQUEST == response['error']['code'] 
Example #9
Source File: test_jsonrpc_errors.py    From django-modern-rpc with MIT License 6 votes vote down vote up
def test_jsonrpc_invalid_request_2(all_rpc_url):

    # Missing 'jsonrpc' in payload

    headers = {'content-type': 'application/json'}
    payload = {
        "method": 'add',
        "params": [5, 6],
        # "jsonrpc": "2.0",
        "id": random.randint(1, 1000),
    }
    req_data = json.dumps(payload, cls=DjangoJSONEncoder)
    response = requests.post(all_rpc_url, data=req_data, headers=headers).json()

    assert 'Missing parameter "jsonrpc"' in response['error']['message']
    assert RPC_INVALID_REQUEST == response['error']['code'] 
Example #10
Source File: conftest.py    From photonix with GNU Affero General Public License v3.0 6 votes vote down vote up
def post_graphql(
        self,
        query,
        variables=None,
        permissions=None,
        check_no_permissions=True,
        **kwargs,
    ):
        """Dedicated helper for posting GraphQL queries.
        Sets the `application/json` content type and json.dumps the variables
        if present.
        """
        data = {"query": query}
        if variables is not None:
            data["variables"] = variables
        if data:
            data = json.dumps(data, cls=DjangoJSONEncoder)
        kwargs["content_type"] = "application/json"

        if permissions:
            if check_no_permissions:
                response = super().post(API_PATH, data, **kwargs)
                assert_no_permission(response)
            self.user.user_permissions.add(*permissions)
        return super().post(API_PATH, data, **kwargs) 
Example #11
Source File: models.py    From hypha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_form_submission(self, form):
        cleaned_data = form.cleaned_data

        for name, field in form.fields.items():
            if isinstance(field, FileField):
                file_data = cleaned_data[name]
                if file_data:
                    file_name = file_data.name
                    file_name = webform_storage.generate_filename(file_name)
                    upload_to = os.path.join('webform', str(self.id), file_name)
                    saved_file_name = webform_storage.save(upload_to, file_data)
                    file_details_dict = {name: webform_storage.url(saved_file_name)}
                    cleaned_data.update(file_details_dict)
                else:
                    del cleaned_data[name]

        form_data = json.dumps(cleaned_data, cls=DjangoJSONEncoder)
        return self.get_submission_class().objects.create(
            form_data=form_data,
            page=self,
        ) 
Example #12
Source File: views.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def position_list(request):
    return render(request, 'site/position_list.html', {
        'positions': Position.objects.filter(owner=request.user),
        'user_data_json': json.dumps(get_user_data(request), cls=DjangoJSONEncoder),
    }) 
Example #13
Source File: graphics.py    From orcamentos with MIT License 5 votes vote down vote up
def percent_type_customer_json(request):
    ''' Porcentagem de tipos de clientes '''
    data = Customer.objects.values('customer_type')\
        .annotate(value=Count('customer_type'))\
        .order_by('customer_type').values('customer_type', 'value')
    total = Customer.objects.all().count()
    # Precisa reescrever o dicionário com os campos do gráfico,
    # que são: 'label' e 'value'. E ainda retornar o get_customer_type_display.
    lista = [{'label': CUSTOMER_DICT[item['customer_type']],
              'value': int((item['value'] / total) * 100)} for item in data]
    s = json.dumps(lista, cls=DjangoJSONEncoder)
    print(s)
    return HttpResponse(s) 
Example #14
Source File: graphics.py    From orcamentos with MIT License 5 votes vote down vote up
def proposal_per_status_json(request):
    '''
    JSON used to generate the graphic
    Quantidade de orçamentos por status
    '''
    data = Proposal.objects.values('status')\
        .annotate(value=Count('status'))\
        .order_by('status').values('status', 'value')
    # Precisa reescrever o dicionário com os campos do gráfico,
    # que são: 'label' e 'value'. E ainda retornar o get_status_display.
    lista = [{'label': STATUS_DICT[item['status']],
              'value': item['value']} for item in data]
    s = json.dumps(lista, cls=DjangoJSONEncoder)
    return HttpResponse(s) 
Example #15
Source File: fields.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def get_prep_value(self, value):
        return json.dumps(value, cls=DjangoJSONEncoder) 
Example #16
Source File: graphics.py    From orcamentos with MIT License 5 votes vote down vote up
def contract_more_expensive_json(request):
    ''' 5 contratos mais caros '''
    c = Contract.objects.all().values(
        'proposal__work__name_work',
        'proposal__price').order_by('-proposal__price')[:5]
    s = json.dumps(list(c), cls=DjangoJSONEncoder)
    return HttpResponse(s) 
Example #17
Source File: graphics.py    From orcamentos with MIT License 5 votes vote down vote up
def contract_total_per_month_json(request):
    ''' valor total fechado por mês no ano '''
    c = Contract.objects.all().values('created', 'proposal__price') \
        .filter(is_canceled=False)
    gr = itertools.groupby(c, lambda d: d.get('created').strftime('%Y-%m'))
    dt = [{'month': month, 'total': sum(
        [x['proposal__price'] for x in total])} for month, total in gr]
    s = json.dumps(list(dt), cls=DjangoJSONEncoder)
    return HttpResponse(s) 
Example #18
Source File: factories.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate(self, step, params):
        params = self.build_form(params)
        blocks = super().generate(step, params)
        ret_val = list()
        # Convert to JSON so we can add id before create
        for block_name, value in blocks:
            block = self.factories[block_name]._meta.model()
            value = block.get_prep_value(value)
            ret_val.append({'type': block_name, 'value': value, 'id': str(uuid.uuid4())})
        return json.dumps(ret_val, cls=DjangoJSONEncoder) 
Example #19
Source File: tests.py    From uclapi with MIT License 5 votes vote down vote up
def test_userdeny_user_does_not_exist(self):
        dev_user_ = User.objects.create(
            email="testdev@ucl.ac.uk",
            cn="test",
            given_name="Test Dev",
            employee_id='testdev01'
        )
        app_ = App.objects.create(
            user=dev_user_,
            name="An App",
            callback_url="www.somecallbackurl.com/callback"
        )

        signer = signing.TimestampSigner()
        # Generate a random state for testing
        state = ''.join(
            random.choices(string.ascii_letters + string.digits, k=32)
        )

        response_data = {
            "client_id": app_.client_id,
            "state": state,
            "user_upi": "bogus"
        }

        response_data_str = json.dumps(response_data, cls=DjangoJSONEncoder)
        signed_data = signer.sign(response_data_str)

        response = self.client.post(
            '/oauth/user/deny',
            {
                'signed_app_data': signed_data
            },
        )

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json()["error"],
                         ("User does not exist. This should never occur. "
                          "Please contact us at "
                          "isd.apiteam@ucl.ac.uk or on github.")) 
Example #20
Source File: context_processors.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def user_data_json(request):
    return {
        'user_data_json': lambda: json.dumps(dict(request.user_data), separators=(',', ':'), cls=DjangoJSONEncoder),
    } 
Example #21
Source File: models.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_form_submission(self, form):
        """
        Accepts form instance with submitted data, user and page.
        Creates submission instance.

        You can override this method if you want to have custom creation logic.
        For example, if you want to save reference to a user.
        """

        return self.get_submission_class().objects.create(
            form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder),
            page=self,
        ) 
Example #22
Source File: views.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def close_response(request):
    ajax = request.is_ajax() or 'ajax' in request.GET
    if ajax:
        return HttpResponse(json.dumps(get_user_data(request), cls=DjangoJSONEncoder).encode(),
                            content_type='text/plain')
    redirect_path = request.GET['next'] if request.GET.get('next', '').startswith('/') else reverse('site.index')
    return redirect(redirect_path) 
Example #23
Source File: models.py    From django-channels-react-multiplayer with MIT License 5 votes vote down vote up
def as_json(self):
        return dict(
            id=self.id,
            message=self.message,
            message_type=self.message_type,
            created_at=json.dumps(self.created_at, cls=DjangoJSONEncoder),
            username=self.username,
        ) 
Example #24
Source File: response.py    From openhgsenti with Apache License 2.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(JsonResponse, self).__init__(content=data, **kwargs) 
Example #25
Source File: views.py    From django-react-djangocon2015 with MIT License 5 votes vote down vote up
def serialized_hydration(request):
    photos = PhotoSerializer(Photo.objects.all(), many=True)
    favorites = FavoriteSerializer(Favorite.objects.all(), many=True)
    initial_data = json.dumps({
        'photos': photos.data,
        'favorites': favorites.data,
    }, cls=DjangoJSONEncoder)
    return render(request, 'serialized.html', {
        'initial_data': initial_data
    }) 
Example #26
Source File: pwa.py    From django-progressive-web-app with MIT License 5 votes vote down vote up
def js(obj):
    """ Transform a python object so it can be safely used in javascript/JSON. """
    return mark_safe(json.dumps(obj, cls=DjangoJSONEncoder)) 
Example #27
Source File: conftest.py    From photonix with GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self, data=None, **kwargs):
        """Send a POST request.
        This wrapper sets the `application/json` content type which is
        more suitable for standard GraphQL requests and doesn't mismatch with
        handling multipart requests in Graphene.
        """
        if data:
            data = json.dumps(data, cls=DjangoJSONEncoder)
        kwargs["content_type"] = "application/json"
        return super().post(API_PATH, data, **kwargs) 
Example #28
Source File: response.py    From python with Apache License 2.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(JsonResponse, self).__init__(content=data, **kwargs) 
Example #29
Source File: fields.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_prep_value(self, value):
        if isinstance(value, StreamValue) and not(value) and value.raw_text is not None:
            # An empty StreamValue with a nonempty raw_text attribute should have that
            # raw_text attribute written back to the db. (This is probably only useful
            # for reverse migrations that convert StreamField data back into plain text
            # fields.)
            return value.raw_text
        else:
            return json.dumps(self.stream_block.get_prep_value(value), cls=DjangoJSONEncoder) 
Example #30
Source File: views.py    From bottle-yang-extractor-validator with 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')