當前位置: 首頁>>代碼示例>>Python>>正文


Python json.DjangoJSONEncoder方法代碼示例

本文整理匯總了Python中django.core.serializers.json.DjangoJSONEncoder方法的典型用法代碼示例。如果您正苦於以下問題:Python json.DjangoJSONEncoder方法的具體用法?Python json.DjangoJSONEncoder怎麽用?Python json.DjangoJSONEncoder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.core.serializers.json的用法示例。


在下文中一共展示了json.DjangoJSONEncoder方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: make_message

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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) 
開發者ID:codeforboston,項目名稱:cornerwise,代碼行數:19,代碼來源:request.py

示例2: get_holding

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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) 
開發者ID:OnGridSystems,項目名稱:CATEd,代碼行數:18,代碼來源:views.py

示例3: getLasted

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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) 
開發者ID:Superbsco,項目名稱:weibo-analysis-system,代碼行數:20,代碼來源:views.py

示例4: post_graphql

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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) 
開發者ID:damianmoore,項目名稱:photonix,代碼行數:27,代碼來源:conftest.py

示例5: _preencode

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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 
開發者ID:c3nav,項目名稱:c3nav,代碼行數:19,代碼來源:json.py

示例6: write

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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 
開發者ID:g0v,項目名稱:tw-rental-house-data,代碼行數:22,代碼來源:json_writer.py

示例7: json_in_script_tag

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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) 
開發者ID:CJWorkbench,項目名稱:cjworkbench,代碼行數:24,代碼來源:json_filters.py

示例8: test_jsonrpc_invalid_request_1

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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'] 
開發者ID:alorence,項目名稱:django-modern-rpc,代碼行數:18,代碼來源:test_jsonrpc_errors.py

示例9: test_jsonrpc_invalid_request_2

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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'] 
開發者ID:alorence,項目名稱:django-modern-rpc,代碼行數:18,代碼來源:test_jsonrpc_errors.py

示例10: test_jsonrpc_invalid_request_3

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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'] 
開發者ID:alorence,項目名稱:django-modern-rpc,代碼行數:18,代碼來源:test_jsonrpc_errors.py

示例11: process_form_submission

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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,
        ) 
開發者ID:OpenTechFund,項目名稱:hypha,代碼行數:23,代碼來源:models.py

示例12: json_validate_rfc

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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') 
開發者ID:YangCatalog,項目名稱:bottle-yang-extractor-validator,代碼行數:7,代碼來源:views.py

示例13: json_validate_draft

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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') 
開發者ID:YangCatalog,項目名稱:bottle-yang-extractor-validator,代碼行數:7,代碼來源:views.py

示例14: datatracker_rfc

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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') 
開發者ID:YangCatalog,項目名稱:bottle-yang-extractor-validator,代碼行數:14,代碼來源:views.py

示例15: datatracker_draft

# 需要導入模塊: from django.core.serializers import json [as 別名]
# 或者: from django.core.serializers.json import DjangoJSONEncoder [as 別名]
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') 
開發者ID:YangCatalog,項目名稱:bottle-yang-extractor-validator,代碼行數:14,代碼來源:views.py


注:本文中的django.core.serializers.json.DjangoJSONEncoder方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。