How to obtain JSON value from Post in a web.py server app?

守給你的承諾、 提交于 2019-12-10 10:15:13

问题


Am using Python 2.7.6 along with web.py server to experiment with some simple Rest calls...

Wish to send a JSON payload to my server and then print the value of the payload...

Sample payload

{"name":"Joe"}

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()

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...


回答1:


You have to parse the 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()

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.



来源:https://stackoverflow.com/questions/33770800/how-to-obtain-json-value-from-post-in-a-web-py-server-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!