本文整理汇总了Python中django.core.serializers.serialize方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.serialize方法的具体用法?Python serializers.serialize怎么用?Python serializers.serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.serializers
的用法示例。
在下文中一共展示了serializers.serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: command
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def command(request):
data = json.loads(request.POST.get('data', '{}'))
func = getattr(commands, data['command'], None)
if func:
if request.user.has_perm(func.permission):
output, status = func(data)
output = serializers.serialize('json', output, ensure_ascii=False)
else:
output = json.dumps({'error': 'permission denied'})
status = 403
else:
output = json.dumps({'error': 'unrecognized command'})
status = 400
resp = HttpResponse(output, content_type='application/json;charset=utf-8')
if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
return HttpResponse(
json.dumps(connection.queries, ensure_ascii=False, indent=1),
status=status,
content_type='application/json;charset=utf-8',
)
return resp
示例2: properties_geojson
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def properties_geojson(request):
"""
Retrieves properties given the querystring params, and
returns them as GeoJSON.
"""
ne = request.GET["ne"].split(",")
sw = request.GET["sw"].split(",")
lookup = {
"point__contained": Polygon.from_bbox((sw[1], sw[0], ne[1], ne[0])),
"bedrooms__gte": request.GET["min-bedrooms"],
"bedrooms__lte": request.GET["max-bedrooms"],
"bathrooms__gte": request.GET["min-bathrooms"],
"car_spaces__gte": request.GET["min-car-spaces"],
"property_type__in": request.GET["property-types"].split(",")
}
if request.GET["nearest-school"] != "1":
lookup["nearest_school_distance__lt"] = int(request.GET["nearest-school"]) - 1
if request.GET["nearest-train-station"] != "1":
lookup["nearest_train_station_distance__lt"] = int(request.GET["nearest-train-station"]) - 1
properties = Property.objects.filter(**lookup)
json = serialize("geojson", properties, geometry_field="point")
return HttpResponse(json, content_type="application/json")
示例3: post
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def post(self, request, *args, **kwargs):
obj_list = []
pessoa = Pessoa.objects.get(pk=request.POST['pessoaId'])
cliente = Cliente.objects.get(pk=request.POST['pessoaId'])
obj_list.append(cliente)
if pessoa.endereco_padrao:
obj_list.append(pessoa.endereco_padrao)
if pessoa.email_padrao:
obj_list.append(pessoa.email_padrao)
if pessoa.telefone_padrao:
obj_list.append(pessoa.telefone_padrao)
if pessoa.tipo_pessoa == 'PJ':
obj_list.append(pessoa.pessoa_jur_info)
elif pessoa.tipo_pessoa == 'PF':
obj_list.append(pessoa.pessoa_fis_info)
data = serializers.serialize('json', obj_list, fields=('indicador_ie', 'limite_de_credito', 'cnpj', 'inscricao_estadual', 'responsavel', 'cpf', 'rg', 'id_estrangeiro', 'logradouro', 'numero', 'bairro',
'municipio', 'cmun', 'uf', 'pais', 'complemento', 'cep', 'email', 'telefone',))
return HttpResponse(data, content_type='application/json')
示例4: SpiderAPI
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def SpiderAPI(request):
pass
# all = TweetsInfo.objects.filter(UserInfo_id=text)
# for e in all:
# mm = ()
# s = SnowNLP(e.Content.replace('转发理由','').replace('转发内容', '').replace('原始用户', '').replace('转发微博已被删除', ''))
# for i in s.tags:
# mm += i
# TweetsInfo.objects.filter(_id=e._id).update(tags=s.keywords(5))
# TweetsInfo.objects.filter(_id=e._id).update(pinyin=mm)
# TweetsInfo.objects.filter(_id=e._id).update(sentiments=str(s.sentiments))
# print(s.keywords(5))
# else:
# text = "输入微博Id错误,请重新输入!"
# res['ok'] = text
# try:
# resp = Target.objects.values('uid','cookie','add_time')
# resp = json.dumps(resp,cls=JsonCustomEncoder)
# resp = serializers.serialize("json", Target.objects.all().order_by("-id")[:1])
# wb = Weibo(uid,cookie)
# mm = wb.get_comment_info('4358934418168720')
# mm = wb.get_weibo_info()
# mm = wb.getTest()
# except Exception as e:
# return HttpResponse('拉取数据库数据失败: %s' % e)
示例5: _perform_version_update
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def _perform_version_update(version, update_data):
from reversion import revisions
if hasattr(version, "object_version"):
local_obj = version.object_version.object
else:
local_obj = version._object_version.object
for field, value in update_data.items():
setattr(local_obj, field, value)
if hasattr(revisions, '_get_options'):
version_options = revisions._get_options(get_reversion_version_model(version))
version_format = version_options.format
version_fields = version_options.fields
else:
version_adapter = revisions.get_adapter(get_reversion_version_model(version))
version_format = version_adapter.get_serialization_format()
version_fields = list(version_adapter.get_fields_to_serialize())
version.serialized_data = serializers.serialize(
version_format,
(local_obj,),
fields=version_fields
)
version.save()
示例6: test_field_serialization
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def test_field_serialization(self):
"""Ensure VersatileImageField and PPOIField serialize correctly."""
output = serializers.serialize(
'json',
VersatileImageTestModel.objects.filter(img_type='png')
)
self.assertJSONEqual(
output,
[
{
"fields": {
"img_type": "png",
"ppoi": "0.5x0.5",
"width": 601,
"height": 203,
"image": "python-logo.png",
"optional_image_3": "",
"optional_image_2": "",
"optional_image": "python-logo.jpg"
},
"model": "tests.versatileimagetestmodel",
"pk": self.png.pk
}
]
)
示例7: statuses
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def statuses(request):
from servo.models import Status
results = Status.objects.all()
data = serialize('json', results)
return HttpResponse(data, content_type='application/json')
示例8: locations
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def locations(request):
queryset = Location.objects.all()
serializer = 'json'
if request.META['HTTP_USER_AGENT'].startswith('curl'):
serializer = 'yaml'
data = serialize(serializer, queryset)
return HttpResponse(data)
示例9: queues
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def queues(request):
queryset = Queue.objects.all()
data = serialize('json', queryset, fields=('pk', 'title'))
return HttpResponse(data, content_type='application/json')
示例10: list_members
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def list_members(self, request, *args, **kwargs):
"""
List all members of this project.
"""
project = self.get_object()
users = project.members.all()
data = serializers.serialize("json", users)
return Response(json.loads(data), status=status.HTTP_200_OK)
示例11: serialize_result
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def serialize_result(data_func, filename):
print("creating %s.json" % (filename))
start = time.time()
objs = data_func()
data = serializers.serialize("json", objs, sort_keys=True, indent=1)
fh = open('fixtures/' + filename + '.json', 'w')
fh.write(data)
fh.close()
done = time.time()
#print "(%.1f s)" % (done-start)
示例12: handle
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def handle(self, *args, **options):
assert settings.DEPLOY_MODE != 'production'
raise NotImplementedError()
n_fake = 200
fake_students = [Person(
emplid=str(500000000 + i),
userid='fake%03i' % (i,),
last_name='Fake',
first_name=random_name(8),
middle_name=random_name(5),
title=random.choice(['Mr', 'M', 'Ms', 'Dr', 'Count'])
) for i in range(n_fake)]
for p in fake_students:
p.pref_first_name = random.choice([None, p.first_name[:4]])
students_per_class = 10
for o in CourseOffering.objects.all():
student_people = random.choices(fake_students, k=students_per_class)
student_members = [
Member(person=p, offering=o, role='STUD', added_reason='AUTO', credits=3, career='UGRD')
for p in student_people
]
data.append(student_members)
print(serializers.serialize('json', itertools.chain(*data), indent=2))
示例13: poc_list_json
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def poc_list_json(request):
data = models.poc_list.objects.all()
#print help(data.__dict__) #内置数据库对象 转为 字典类型
#获取数据库的poc列表
#print local_json
response_json = serializers.serialize("json", data)
#print response_json
return HttpResponse(response_json)
"""
| appName = <django.db.models.query_utils.DeferredAttribute object>
| appPowerLink = <django.db.models.query_utils.DeferredAttribute object>
| appVersion = <django.db.models.query_utils.DeferredAttribute object>
| author = <django.db.models.query_utils.DeferredAttribute object>
| category = <django.db.models.query_utils.DeferredAttribute object>
| createDate = <django.db.models.query_utils.DeferredAttribute object>
| desc = <django.db.models.query_utils.DeferredAttribute object>
| filename = <django.db.models.query_utils.DeferredAttribute object>
| install_requires = <django.db.models.query_utils.DeferredAttribute object>
| name = <django.db.models.query_utils.DeferredAttribute object>
| objects = <django.db.models.manager.Manager object>
| references = <django.db.models.query_utils.DeferredAttribute object>
| samples = <django.db.models.query_utils.DeferredAttribute object>
| updateDate = <django.db.models.query_utils.DeferredAttribute object>
| version = <django.db.models.query_utils.DeferredAttribute object>
| vulID = <django.db.models.query_utils.DeferredAttribute object>
| vulType = <django.db.models.query_utils.DeferredAttribute object>
"""
#客户端和服务端重用api
示例14: get
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def get(self, request):
if request.user.is_authenticated:
# data = request.data
key = request.GET.get('key')
search_list = Product.objects.filter(title__contains=key)
# paginator = Paginator(search_list, 5)
# try:
# search = paginator.page(data.get('page'))
# except PageNotAnInteger:
# search = paginator.page(1)
# except EmptyPage:
# search = paginator.page(paginator.num_pages)
# # print(search)
# search_list = json.loads(serializers.serialize("json", search_list))
ser = ProductSerializer(instance=search_list, many=True)
# print(ser.data)
msg = sort_out_list(request, ser.data)
return Response(msg, 200)
else:
msg = {
'stateCode': 201,
'msg': '没有访问权限'
}
return Response(msg, 201)
# 获取我的发布列表
示例15: to_json
# 需要导入模块: from django.core import serializers [as 别名]
# 或者: from django.core.serializers import serialize [as 别名]
def to_json(self, objects):
return serializers.serialize('json', objects)