2015-11-18 55 views
2

上午使用Python 2.7.6與web.py服務器一起嘗試一些簡單的REST調用...如何從web.py服務器應用程序中獲取Post的JSON值?

要發送一個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! 

感謝您在百忙之中閱讀本文時...

回答

7

你必須解析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,這會引發錯誤。

相關問題