我正在尝试使用python urllib将JSON数据发送到我的django Web应用程序,但是没有运气。
这是我的代码;
Python应用程序:
url = "http://127.0.0.1:8000/web_app"
values = {'name':'Paul','age':12}
jdata = {'data':values}
data = urllib.urlencode(values)
req = urllib2.Request(url, data, {'Content-Type':'application/json'})
try:
resp = urllib2.urlopen(req)
the_result = resp.read()
except urllib2.HTTPError, e:
return "Reques Failed!"
我的Django Web应用程序:
@csrf_exempt
def web_app(request):
print "In My webapp" # This never get printed!
data = request.POST['data']
return HttpResponse("Thankyou...")
该请求似乎没有命中Django
web_app
函数,因为未执行该函数中的第一次打印!添加:
注意,如果我从urllib2.request中的请求中删除数据,那么一切都会按预期进行!!
我想念什么?
最佳答案
您的urlconf是什么样的?如果在设置中看起来像'^web_app/$'
和APPEND_SLASH=True
(默认设置),则需要使用"http://127.0.0.1:8000/web_app/"
(请注意后缀斜杠)。否则,如果没有匹配项,Django将尝试将/web_app
重定向到/web_app/
,然后抱怨重定向POST
请求。
另外,为HTTP请求设置'Content-Type':'application/json'
毫无意义,您可以设置此参数并通过向其传递JSON转储的字符串来破坏the requirement of urllib2;但是您应该自己解析request.body
而不是使用request.POST
。 application/json
通常用于指定响应的Content-Type
。
关于python - 如何通过Python urllib将JSON数据发送到Django应用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10654249/