码迷,mamicode.com
首页 > 编程语言 > 详细

python http server handle json

时间:2017-08-07 22:22:54      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:http   lib   ons   utf-8   add   span   pre   forever   ade   

用Python实现一个http server

# python2
# coding = utf-8

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import json

class RequestHandler(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header(Content-type, application/json)
        self.end_headers()

    def do_GET(self):
        response = {
            status:SUCCESS,
            data:hello from server
        }

        self._set_headers()
        self.wfile.write(json.dumps(response))

    def do_POST(self):
        content_length = int(self.headers[Content-Length])
        post_data = self.rfile.read(content_length)
        print post data from client:
        print post_data

        response = {
            status:SUCCESS,
            data:server got your post data
        }
        self._set_headers()
        self.wfile.write(json.dumps(response))

def run():
    port = 80
    print(Listening on localhost:%s % port)
    server = HTTPServer((‘‘, port), RequestHandler)
    server.serve_forever()

run()

 

python post json

# python2
# coding = utf-8

import json
import urllib2

data = {
    key1:value1,
    key2:value2
}

req = urllib2.Request(http://server_ip:server_port)
req.add_header(Content-Type, application/json)

response = urllib2.urlopen(req, json.dumps(data))

print(response.read())

 

python http server handle json

标签:http   lib   ons   utf-8   add   span   pre   forever   ade   

原文地址:http://www.cnblogs.com/gattaca/p/7301282.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!