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


Python serializers.serialize方法代碼示例

本文整理匯總了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 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:23,代碼來源:api.py

示例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") 
開發者ID:googlemaps,項目名稱:property-finder,代碼行數:26,代碼來源:views.py

示例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') 
開發者ID:thiagopena,項目名稱:djangoSIGE,代碼行數:24,代碼來源:ajax_views.py

示例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) 
開發者ID:Superbsco,項目名稱:weibo-analysis-system,代碼行數:27,代碼來源:tests.py

示例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() 
開發者ID:druids,項目名稱:django-GDPR,代碼行數:24,代碼來源:model_anonymizers.py

示例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
                }
            ]
        ) 
開發者ID:respondcreate,項目名稱:django-versatileimagefield,代碼行數:27,代碼來源:tests.py

示例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') 
開發者ID:fpsw,項目名稱:Servo,代碼行數:7,代碼來源:api.py

示例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) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:9,代碼來源:api.py

示例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') 
開發者ID:fpsw,項目名稱:Servo,代碼行數:6,代碼來源:api.py

示例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) 
開發者ID:wangtaoking1,項目名稱:hummer,代碼行數:11,代碼來源:views.py

示例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) 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:12,代碼來源:devtest_importer.py

示例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)) 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:29,代碼來源:load_demo_data.py

示例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 
開發者ID:vulscanteam,項目名稱:vulscan,代碼行數:33,代碼來源:views.py

示例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)


# 獲取我的發布列表 
開發者ID:michwh,項目名稱:onehome-server,代碼行數:30,代碼來源:views.py

示例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) 
開發者ID:tabalinas,項目名稱:jsgrid-django,代碼行數:4,代碼來源:views.py


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