本文整理匯總了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)
示例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)
示例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)
示例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)
示例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
示例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
示例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)
示例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']
示例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']
示例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']
示例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,
)
示例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')
示例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')
示例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')
示例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')