• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils.to_dict函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中utils.to_dict函数的典型用法代码示例。如果您正苦于以下问题:Python to_dict函数的具体用法?Python to_dict怎么用?Python to_dict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了to_dict函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: UserHandler

def UserHandler(request, user_id=None):
    if request.method == 'GET' and user_id is None:
        users = User.objects.all()
        data = []

        for user in users:
            user_dict = to_dict(user)
            user_dict.pop("password", None)
            data.append(user_dict)

        return JsonResponse(data, safe=False)

    if request.method == 'GET' and user_id is not None:
        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return JsonResponse({"error": "User does not exist"}, status=404)

        user_dict = to_dict(user)
        user_dict.pop("password", None)
        return JsonResponse(user_dict, status=200)

    if request.method == "POST":
        body = parseJSON(request.body)
        try:
            username = body["username"]
            password = body["password"]
        except (ValueError, KeyError):
            return JsonResponse({'error': 'JSON is invalid'}, status=409)

        try:
            user = User.objects.create_user(username, None, password)
            user.save()
        except IntegrityError:
            return JsonResponse({'error': 'Username already taken'}, status=409)

        token = Token.objects.get(user=user)
        if token is None:
            token = Token.objects.create(user=user)
        jsonresponse = {
            "username": user.username,
            "firstname": user.first_name,
            "lastname": user.last_name,
            "email": user.email
        }

        response = JsonResponse(jsonresponse)
        response["Authorization"] = token

        return response
开发者ID:egetin,项目名称:otitcode-wiki,代码行数:50,代码来源:views.py


示例2: write_to_elasticsearch

def write_to_elasticsearch(conn, data, xen_index):
    conn.indices.create(index=xen_index, body=PS_REVIEWERS_MAPPING,
                        ignore=400)

    columns = data.columns.values.tolist()

    uniq_id = 0
    bulk_doc = []

    for row in data.itertuples():
        uniq_id = uniq_id + 1
        doc = to_dict(row, columns)

        header = {
            "_index": xen_index,
            "_type": "patchserie",
            "_id": uniq_id,
            "_source": doc
        }

        bulk_doc.append(header)
        if uniq_id % 5000 == 0:
            helpers.bulk(conn, bulk_doc)
            bulk_doc = []

    helpers.bulk(conn, bulk_doc)
开发者ID:dicortazar,项目名称:xen-code-review-analysis,代码行数:26,代码来源:xen_analysis_ps.py


示例3: create

 def create(self, request):
     """
     POST
     Insertar un nuevo subtipo de evento
     :param request:
     :return :
     {status: True/False, data:{datos del subtipo de evento}
     """
     try:
         params = utils.get_params(request)
         if params.get('delete'):
             return SubTipo_EventosViewSet().delete(request)
         self.logger.info('INICIO WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         resul = SubTipo_Evento.objects.create(codigo=params.get('codigo'), nombre=params.get('nombre'))
         if resul.id:
             resul = utils.to_dict(dict(status=True, data=resul))
             resul_status = status.HTTP_200_OK
         else:
             resul = dict(message=resul['message'])
             resul_status = status.HTTP_400_BAD_REQUEST
             self.logger.info('FIN WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username,
                               resul))
         return Response(resul, status=resul_status)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('FIN WS - SUBTIPOEVENTOSVIEW CREATE del usuario: %s con params: %s %s' %
                              (request.user.email if hasattr(request.user, 'email') else request.user.username,
                               resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
开发者ID:gabriel-stan,项目名称:gestion-tfg,代码行数:31,代码来源:views.py


示例4: save

  def save(self):
    id = self.request.get('id')
    user = users.get_current_user()

    script = None
    if id:
      script = Script.get_by_id(int(id))

    if not script:
      script = Script()

    if script.owner and (not user or script.owner.user_id() != user.user_id()):
      script = Script()

    script.title = self.request.get('title')
    script.data = self.request.get('text')
    if user:
      script.owner = user

    key = script.put()

    scriptDict = utils.to_dict(script);
    scriptDict['data'] = script.data
    scriptDict['title'] = script.title
    scriptDict['id'] = key.id()

    self.response.out.write(json.dumps(scriptDict))
开发者ID:peteblois,项目名称:apps.blois.us,代码行数:27,代码来源:index.py


示例5: character_search

def character_search(**args):
    info = to_dict(args)
    for field in ['modulus', 'conductor', 'order']:
        info[field] = info.get(field, '')
    query = {}
    print "args = ", args
    if 'natural' in args:
        label = info.get('natural', '')
        try:
            modulus = int(str(label).partition('.')[0])
            number = int(str(label).partition('.')[2])
        except ValueError:
            return "<span style='color:red;'>ERROR: bad query</span>"
        return redirect(url_for("render_webpage_label", modulus=modulus, number=number))
    else:
        for field in ['modulus', 'conductor', 'order']:
            if info.get(field):
                query[field] = parse_range(info[field])
        info["bread"] = [('Dirichlet Characters', url_for("render_Character")), ('search results', ' ')]
        info['credit'] = 'Sage'
        if (len(query) != 0):
            from sage.modular.dirichlet import DirichletGroup
            info['contents'] = charactertable(query)
            info['title'] = 'Dirichlet Characters'
            return render_template("dirichlet_characters/character_search.html", **info)
        else:
            return "<span style='color:red;'>ERROR: bad query</span>"
开发者ID:anneschilling,项目名称:lmfdb,代码行数:27,代码来源:DirichletCharacter.py


示例6: get

 def get(self):
     bio = models.Biography.all().get()
     if not bio:
         biod = {}
     else:
         biod = utils.to_dict(bio)
     self.renderjson('bio.html', biod)
开发者ID:jpablobr,项目名称:groupies-ftw,代码行数:7,代码来源:handlers.py


示例7: put

 def put(self, request):
     try:
         params = utils.get_params(request)
         self.logger.info('INICIO WS - TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con parametros: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, params))
         if request.user.has_perm('tfgs.tfg_asig.change') or request.user.is_admin:
             tfg = Tfg.objects.get(titulo=params.get('tfg'))
             tfg_asig = Tfg_Asig.objects.get(tfg=tfg)
             serializer = self.serializer_class(tfg)
             params = json.loads(params.get('datos'))
             resul = serializer.update(tfg_asig, params)
             if resul['status']:
                 resul = utils.to_dict(resul)
                 resul_status = status.HTTP_200_OK
             else:
                 resul = dict(message=resul['message'])
                 resul_status = status.HTTP_400_BAD_REQUEST
         else:
             resul = dict(message="Sin privilegios")
             resul_status = status.HTTP_400_BAD_REQUEST
         self.logger.info('FIN WS - TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con resultado: %s' %
                          (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=resul_status)
     except Tfg.DoesNotExist:
         resul = dict(message="El tfg indicado no existe")
         self.logger.error('TFGASIGVIEWCONVOCATORIA PUT del usuario: %s con resultado: %s' %
                           (request.user.email if hasattr(request.user, 'email') else request.user.username, resul))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         resul = dict(status=False, message="Error en la llamada")
         self.logger.critical('TFGASIGVIEWCONVOCATORIA PUT: %s %s' % (resul, e))
         return Response(resul, status=status.HTTP_400_BAD_REQUEST)
开发者ID:gabriel-stan,项目名称:gestion-tfg,代码行数:32,代码来源:views.py


示例8: get

 def get(self, obj_t, identifier, *args):
     cls = getattr(sys.modules['core.model'], obj_t)
     
     # dispatch put to that model class. all model classes need to a subclass model.RESTModel
     obj = utils.to_dict(cls.get(int(identifier)))
     
     return self.prep_json_response(200, message = obj)
开发者ID:helmuthb,项目名称:devfest-at-site,代码行数:7,代码来源:common.py


示例9: CurrentUserHandler

def CurrentUserHandler(request):
    if request.user is None:
        return JsonResponse({"error": "User not logged in"}, status=404)

    if request.method == 'GET':
        user_dict = to_dict(request.user)
        user_dict.pop("password", None)
        return JsonResponse(user_dict)

    if request.method == 'PUT':
        body = parseJSON(request.body)
        try:
            first_name = body["first_name"]
            last_name = body["last_name"]
            email = body["email"]
        except (ValueError, KeyError):
            return JsonResponse({'error': 'JSON is invalid'}, status=409)

        user = request.user
        user.first_name = first_name
        user.last_name = last_name
        user.email = email
        user.save()

        return HttpResponse(status=200)

    if request.method == 'DELETE':
        request.user.delete()
        return HttpResponse(status=200)
开发者ID:egetin,项目名称:otitcode-wiki,代码行数:29,代码来源:views.py


示例10: get

 def get(self):
   result = []
   course_name = self.request.get('course')
   exercises = db.GqlQuery("SELECT * FROM Exercise WHERE course = :1", \
           course_name)
   for exercise in exercises:
       result.append(utils.to_dict(exercise))
   self.response.out.write(json.dumps(result, sort_keys=True))
开发者ID:navatm,项目名称:beny,代码行数:8,代码来源:main.py


示例11: prepare

 def prepare(self, data=None):
     if not data: return None
     for k,v in data.iteritems():
         if isinstance(v, db.Model):
             data[k] = utils.to_dict(v)
         elif isinstance(v, list) and len(v) and isinstance(v[0], db.Model):
             data[k] = utils.to_dicts(v)
     return data
开发者ID:Gembok,项目名称:Tripin-website,代码行数:8,代码来源:handlers.py


示例12: video

 def video(self, id):
     if not id:
         video = self.m.all().get()
     else:
         video = self.m.get_by_id(id)
     if not video:
         return False
     return utils.to_dict(video)
开发者ID:Gembok,项目名称:Tripin-website,代码行数:8,代码来源:handlers.py


示例13: character_search

def character_search(**args):
    # import base
    info = to_dict(args)
    query = {}
    print args

    if "natural" in args:
        label = info.get("natural", "")
        modulus = int(str(label).partition(".")[0])
        number = int(str(label).partition(".")[2])
        return redirect(url_for("render_webpage_label", modulus=modulus, number=number))
    else:
        for field in ["modulus", "conductor", "order"]:
            if info.get(field):
                query[field] = parse_range(info[field])
        info["bread"] = [("Dirichlet Characters", url_for("render_Character")), ("search results", " ")]
        info["credit"] = "Sage"
        if len(query) != 0:
            count_default = 100
            if info.get("count"):
                try:
                    count = int(info["count"])
                except:
                    count = count_default
            else:
                info["count"] = count_default
                count = count_default

            start_default = 0
            if info.get("start"):
                try:
                    print "Check"
                    start = int(info["start"])
                    if start < 0:
                        print "Check1"
                        start += (1 - (start + 1) / count) * count
                except:
                    print "Check2"
                    start = start_default
            else:
                start = start_default
            from sage.modular.dirichlet import DirichletGroup

            t, texname, number, length = charactertable(query)
            info["characters"] = t
            info["texname"] = texname
            info["number"] = number
            info["len"] = length
            if start >= length:
                print "Check3"
                start -= (1 + (start - length) / count) * count
            if start < 0:
                print "Check4"
                start = 0
            info["start"] = start
            info["title"] = "Dirichlet Characters"
            print start, count, length
            return render_template("dirichlet_characters/character_search.html", **info)
开发者ID:swisherh,项目名称:swisherh-logo,代码行数:58,代码来源:DirichletCharacter.py


示例14: post

    def post(self, obj_t, identifier, *args):
        kvs = json.decode(self.request.body)

        # find model class
        cls = getattr(sys.modules['core.model'], obj_t)

        obj = utils.to_dict(cls.post(int(identifier), kvs))

        return self.prep_json_response(200, message = obj)
开发者ID:helmuthb,项目名称:devfest-at-site,代码行数:9,代码来源:common.py


示例15: article

 def article(self, id):
     if not id:
         item = self.m.all().get()
     else:
         item = self.m.get_by_id(id)
     if not item:
         return False
     itemd = utils.to_dict(item)
     return itemd
开发者ID:jpablobr,项目名称:groupies-ftw,代码行数:9,代码来源:handlers.py


示例16: text

 def text(self, id):
     if not id:
         song = self.q.get()
     else:
         song = models.Song.get_by_id(id)
     songd = utils.to_dict(song)
     songd['album'] = song.album.title
     songd['mp3'] = serve_url % songd['mp3']
     return songd
开发者ID:Gembok,项目名称:Tripin-website,代码行数:9,代码来源:handlers.py


示例17: CommentHandler

def CommentHandler(request, comment_id=None):
    if request.method == "GET" and comment_id is None:
        comments = Comment.objects.all()
        data = []

        for comment in comments:
            comment_dict = to_dict(comment)
            data.append(comment_dict)

        return JsonResponse(data, safe=False)

    if request.method == "GET" and comment_id is not None:
        try:
            comment = Comment.objects.get(pk=comment_id)
        except Comment.DoesNotExist:
            return JsonResponse({"error": "Comment does not exist"}, status=404)

        comment_dict = to_dict(comment)
        return JsonResponse(comment_dict, status=200)
开发者ID:egetin,项目名称:otitcode-wiki,代码行数:19,代码来源:views.py


示例18: put

 def put(self, obj_t, *args):
     kvs = json.decode(self.request.body)
     
     # find model class
     cls = getattr(sys.modules['core.model'], obj_t)
     
     # dispatch put to that model class. all model classes need to a subclass model.RESTModel
     obj = utils.to_dict(cls.put1(kvs))
     
     return self.prep_json_response(200, message = obj)
开发者ID:helmuthb,项目名称:devfest-at-site,代码行数:10,代码来源:common.py


示例19: get

 def get(self):
     try:
         players = [utils.to_dict(player) for player in NFL_Player_2015_M.query.all()]
     except:
         abort(400, response={
             'status': 400,
             'message': 'Players not found'
         })
     else:
         return utils.success(players)
开发者ID:AncillaryStats,项目名称:AS-Rest-Api,代码行数:10,代码来源:player.py


示例20: album

 def album(self, id):
     if not id:
         album = self.m.all().get()
     else:
         album = self.m.get_by_id(id)
     if not album:
         return False
     albumd = utils.to_dict(album)
     albumd['artwork'] = images.get_serving_url(albumd['artwork'], 320)
     albumd['songs'] = self.songs(album)
     return albumd
开发者ID:Gembok,项目名称:Tripin-website,代码行数:11,代码来源:handlers.py



注:本文中的utils.to_dict函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.to_json函数代码示例发布时间:2022-05-26
下一篇:
Python utils.to_bytes函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap