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

Python的HTTP服务实例

时间:2017-06-27 18:36:29      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:self   ase   function   前言   art   服务   code   user   ext   

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服务实例

标签:self   ase   function   前言   art   服务   code   user   ext   

原文地址:http://www.cnblogs.com/Anker/p/7086280.html

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