首页 > 代码库 > Python的HTTP服务实例

Python的HTTP服务实例

1、前言

  今天需要实现一个Pyhton的http服务,与Web的JS进行交换。

2、实例代码

  支持HEAD、GET、POST方法,将参数转换为JSON格式,返回结果以JSON字符串返回。

import timeimport BaseHTTPServerimport urllib import jsonimport base64HOST_NAME = 127.0.0.1 PORT_NUMBER = 8080CONIFRM_PATH = /tmpclass HttpHandler(BaseHTTPServer.BaseHTTPRequestHandler):    def _set_headers(self):        self.send_response(200)        self.send_header(Content-type, text/html)        self.end_headers()    def _json_encode(self, data):        array = data.split(&)        json_data = {}        for item in array:            item = item.split(=, 1)            json_data[item[0]] = item[1]        return json_data    def _get_handler(self, data):        json_data = self._json_encode(data)    def _post_handler(self, data):        retVal = {}        json_data = self._json_encode(data)        file_name = json_data[FileName]        file_data = base64.b64decode(json_data[FileData])         file_path = "%s/%s"% (CONIFRM_PATH, file_name)        fd = open(file_path, w)        fd.write(file_data)        fd.close()        retVal["RetCode"] = 0        return json.dumps(retVal)    def do_HEAD(self):        self._set_headers()    def do_GET(self):        self._set_headers()        #get request params        path = self.path          query = urllib.splitquery(path)          self._get_handler(query[1]);    def do_POST(self):        self._set_headers()        #get post data        post_data = http://www.mamicode.com/self.rfile.read(int(self.headers[content-length]))          post_data = urllib.unquote(post_data).decode("utf-8", ignore)         retStr = self._post_handler(post_data)        self.wfile.write(retStr)if __name__ == __main__:    server_class = BaseHTTPServer.HTTPServer    httpd = server_class((HOST_NAME, PORT_NUMBER), HttpHandler)    print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)    try:        httpd.serve_forever()    except KeyboardInterrupt:        pass    httpd.server_close()    print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

使用NodeJS默认测试如下:

var request = require(‘request‘);// Set the headersvar headers = {    ‘User-Agent‘:       ‘USSL Agent/0.0.1‘,    ‘Content-Type‘:     ‘application/x-www-form-urlencoded‘}// Configure the requestvar options = {    url: ‘http://127.0.0.1:8080/‘,    method: ‘GET‘,    headers: headers,    qs: {‘Method‘:‘Put‘,‘FileName‘: ‘test.doc‘}}// Start the requestrequest(options, function (error, response, body) {    if (!error && response.statusCode == 200) {        console.log(body)    }})var options = {    url: ‘http://127.0.0.1:8080/‘,    method: ‘POST‘,    headers: headers,    form: {‘FileName‘: ‘test-confirm.txt‘, ‘FileData‘: "dGhpcyBpcyBhIGV4YW1wbGU="}}request(options, function (error, response, body) {    if (!error && response.statusCode == 200) {        console.log(body)    }})

 

Python的HTTP服务实例