1. 程式人生 > >Python的HTTP服務實例

Python的HTTP服務實例

user 前言 param err ron head config board imp

1、前言

  今天需要實現一個Pyhton的http服務,與Web的JS進行交換。

2、實例代碼

  支持HEAD、GET、POST方法,將參數轉換為JSON格式,返回結果以JSON字符串返回。

import time
import BaseHTTPServer
import urllib 
import json
import base64

HOST_NAME = 127.0.0.1 
PORT_NUMBER = 8080
CONIFRM_PATH = /tmp

class 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 = 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 headers
var headers = {
    ‘User-Agent‘:       ‘USSL Agent/0.0.1‘,
    ‘Content-Type‘:     ‘application/x-www-form-urlencoded‘
}

// Configure the request
var options = {
    url: ‘http://127.0.0.1:8080/‘,
    method: ‘GET‘,
    headers: headers,
    qs: {‘Method‘:‘Put‘,‘FileName‘: ‘test.doc‘}
}

// Start the request
request(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服務實例