我使用Python2.7.6和web.py服务器来尝试一些简单的Rest调用。。。
希望将json负载发送到我的服务器,然后打印负载的值…
样本有效载荷
{"name":"Joe"}
这是我的python脚本
#!/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命令:
curl -H "Content-Type: application/json" -X POST -d '{"name":"Joe"}' http://localhost:8080/hello
我期待此响应(纯文本):
Hello Joe!
谢谢你抽出时间来读这个…
最佳答案
必须解析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/
请求中的url是cURL
;示例中的url是http://localhost:8080/hello
,这会引发错误。