django 怎么处理前台发送过去的json数据

2025-04-26 02:12:06
推荐回答(3个)
回答1:

#django原始库
import django.http as djangohttp

#django第三方库
import rest_framework.views as rfview
import rest_framework.renderers as rfreader

#自定义库
import CodingPond


class IView( rfview.APIView ):
    renderer_classes = ( rfreader.JSONPRenderer, )

class JSONResponse( djangohttp.HttpResponse ):
    """
    An HttpResponse that renders it's content into JSON.
    """
    def __init__( self, data = None, header = {}, **kwargs ):
        content = rfreader.JSONRenderer().render( data )
        print content
#        content = CodingPond.Authcode_encode( content, "" )
        kwargs['content_type'] = 'application/json'

        super( JSONResponse, self ).__init__( content, **kwargs )
        self._init_header( header )

    def _init_header( self, header ):
        for key, value in header.items():
            self[key] = value

如此,上面是httpTools.IView接口,然后视图继承,分别重写get和post即可

class ClassifyHomeView( httpTools.IView ):
    """
    @attention: 分类主页
    @note: 
      -路径: /classify/init/
      -post: 无
      -返回: {"classify":[分类数据格式]}
    """
    def post( self, request ):
        command = Commands.GetClassifyInfoCommand()
        command.Excute()
        resDic = command.GetResInfo()
        return httpTools.JSONResponse( resDic )

回答2:

json.loads不行吗?

回答3:

自己可以写一个解析数据格式的类文件,应该可行的。