如何从web.py服务器应用程序中的Post获取JSON值? [英] How to obtain JSON value from Post in a web.py server app?
问题描述
我正在使用Python 2.7.6和web.py服务器来尝试一些简单的Rest调用...
Am using Python 2.7.6 along with web.py server to experiment with some simple Rest calls...
希望将JSON有效负载发送到我的服务器,然后打印有效载荷的值...
Wish to send a JSON payload to my server and then print the value of the payload...
示例有效载荷
{"name":"Joe"}
这是我的python脚本
Here's my python script
#!/usr/bin/env python
import web
import json
urls = (
'/hello/', 'index'
)
class index:
def POST(self):
# How to obtain the name key and then print the value?
print "Hello " + value + "!"
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
这是我的cURL命令:
Here's my cURL command:
curl -H "Content-Type: application/json" -X POST -d '{"name":"Joe"}' http://localhost:8080/hello
我期望对此做出响应(纯文本):
Am expecting this for the response (plain text):
Hello Joe!
感谢您抽出宝贵的时间阅读本文...
Thank you for taking the time to read this...
推荐答案
您必须解析json:
#!/usr/bin/env python
import web
import json
urls = (
'/hello/', 'index'
)
class index:
def POST(self):
# How to obtain the name key and then print the value?
data = json.loads(web.data())
value = data["name"]
return "Hello " + value + "!"
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
另外,请确保您的网址是 http:// localhost:8080 / hello /
在您的 cURL
请求中;您的示例中有 http:// localhost:8080 / hello
,这会引发错误。
Also, make sure you're url is http://localhost:8080/hello/
in your cURL
request; you have http://localhost:8080/hello
in your example, which throws an error.
这篇关于如何从web.py服务器应用程序中的Post获取JSON值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!