• Python的HTTP服务实例


    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)
        }
    })
  • 相关阅读:
    创建Hive/hbase相关联的表异常
    CDH5.2+CM5.2+impala2+Spark1.1 集群搭建基础环境准备
    【JavaWeb】(10)微信公众号开发进阶
    Ambari-stack介绍
    OSGi中的ServletContext
    笔试面试1 用C实现C库函数itoa, atoi
    SGU 114. Telecasting station 三分or找中位数
    face++实现人脸识别
    磁盘接口与磁盘扫描
    CSDN开源夏令营 百度数据可视化实践 ECharts(4)
  • 原文地址:https://www.cnblogs.com/Anker/p/7086280.html
Copyright © 2020-2023  润新知