How to obtain JSON value from Post in a web.py ser

2019-05-10 20:35发布

问题:

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.