How to write a web server to handle post (content-type is application/json) in python?
Here comes the detail:
We want to write a web server in Python v2.6.5, and have finished the do_GET
method.
But I don't know how to write the do_POST()
method.
If the post request goes like the following:
POST /employee/111 HT开发者_JAVA技巧TP/1.1
Content-Type: application/json
Content-Length: XX
{"name": "John"}
How to get the JSON data {"name": "John"}
in do_POST()
method?
(prefer standard library)
It'd be greatly appreciated if you can eloborate why and give a sample.
Thank you!
Use the cgi.FieldStorage
class to to handle the data as a form-data avaiable from the POST..
And when you go the portion which is the body of the POST and which in your case is in json
format.
def do_POST(self):
# Parse the form data posted
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
Here is an example illustrating how to do that
And if the content is a proper json, use the json module from the standard library to load to json format and you can deal with it further.
>>> import json
>>> s = '{"name": "john"}'
>>> d = json.loads(s)
In your post, the element {"name": "John"}
is just a string that needs to be json parsed. So first import the json
module and then do json.load
.
import json
post_json_data = json.loads('{"name": "John"}')
To detect where the json data starts you just need to read up to the first {
, everything from there should be part of the json data.
精彩评论