django如何获得post过来的json格式的数据

客户端代码:

def http_post(values):
    json_data = json.dumps(values)
    try:
        req = urllib2.Request(post_server,json_data)   #生成页面请求的完整数据
        response = urllib2.urlopen(req)    # 发送页面请求
    except urllib2.HTTPError,error:
        print "ERROR: ",error.read()

Django端代码:

def recv_data(request):
    if request.method == 'POST':
        received_json_data = json.loads(request.body)
        return received_json_data
    else:
        print 'abc'

程序运行后,client端总是报错:
You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will
display a standard 500 page.

  请问是什么原因啊?!
阅读 55.5k
5 个回答

500django程序执行的时候错误。

目测你POST的数据不是标准的json字符串loads的时候报错

你可以打印一下 request.body

设置 Debug=True

可以看到更详细的报错信息。

解决了了,是json的问题!

def recv_data(request):
    if request.method == 'POST':
        req = json.loads(request.body)
新手上路,请多包涵

if request.method == 'POST':

result = json.loads(request.body.decode()).get('ip')

request.body 得到的是bytes类型的数据,先解码为str类型,也就是说request.body.decode()的结果是一个json字符串,此时json.loads()转为Python字典,然后获取对应值

他说的很明白: 在你的设置文件中你把 'DEBUG = True' 这个 DEBUG 的值改为 false就好了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题