• python3与python2使用python原生SimpleHTTPRequestHandler


    python3 使用时如下:

    #!/usr/bin/env python3
    #coding=utf-8
    from  http.server import SimpleHTTPRequestHandler
    import socketserver
    import os,io,shutil
    import logging
    import cgi
    import sys
    import json
    
    log_path = './logs/run_server_logs.log'
    logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename=log_path)
    class MyHttpHandler(SimpleHTTPRequestHandler):
        
        def _set_headers(self):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
        
        def send_datas(self,contents):
            #指定返回编码
            enc = "UTF-8"
            content = contents.encode(enc)          
            f = io.BytesIO()
            f.write(content)
            f.seek(0)  
            self.send_response(200)  
            self.send_header("Content-type", "text/html; charset=%s" % enc)  
            self.send_header("Content-Length", str(len(contents)))  
            self.end_headers() 
            shutil.copyfileobj(f,self.wfile)
     
        def do_GET(self):
            logging.info("got get request "+str(self.path))
            values = str(self.path)
            self.send_datas('这是get请求'+values)
     
        def do_POST(self):
            logging.info("got post!!")
            datasets = cgi.FieldStorage(fp = self.rfile,headers = self.headers,environ = {'REQUEST_METHOD': 'POST'})
            logging.info(str(datasets))
            id = datasets.getvalue('id')
            name = datasets.getvalue('name')
            msg = "name=="+str(name)+"   id=="+str(id)
            flag = 1
            results = {"status":flag,"msg":msg}
            self.send_datas(json.dumps(results))
            
            
    def start_server():
        server_host = '127.0.0.1'
        server_port = 8080
        httpd = socketserver.TCPServer((server_host,server_port), MyHttpHandler)
        logging.info('
    Start server success ... 
    server_host:'+server_host+'   server_port:'+str(server_port))
        print('exe_server started on '+str(server_host)+' server_port:'+str(server_port))
        httpd.serve_forever()
    
    
    if __name__ == "__main__":
        start_server()

    python2使用时:

    #!/usr/bin/env python
    #coding=utf-8
    from SimpleHTTPServer import SimpleHTTPRequestHandler
    import SocketServer
    import os,io,shutil
    import logging
    import cgi
    import urlparse
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    log_path = './logs/run_server_logs.log'
    logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename=log_path)
    class MyHttpHandler(SimpleHTTPRequestHandler):
        
        def _set_headers(self):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
        
        def send_datas(self,contents):
            #指定返回编码
            enc = "UTF-8"
            #contents = contents.encode(enc)          
            f = io.BytesIO()
            f.write(contents)
            f.seek(0)  
            self.send_response(200)  
            self.send_header("Content-type", "text/html; charset=%s" % enc)  
            self.send_header("Content-Length", str(len(contents)))  
            self.end_headers() 
            shutil.copyfileobj(f,self.wfile)
     
        def do_GET(self):
            logging.info("got get request "+str(self.path))
            values = str(self.path)
            self.send_datas('get请求方式'+values)
                  
        def do_POST(self):
            logging.info("got post!!")
            datasets = cgi.FieldStorage(fp = self.rfile,headers = self.headers,environ = {'REQUEST_METHOD': 'POST'})
            logging.info(str(datasets))
            id = datasets.getvalue('id')
            name = datasets.getvalue('name')
            
            msg = "name=="+str(name)+"   id=="+str(id)
            flag = 1
            results = {'status':flag,'msg':msg}
            self.send_datas(str(results))
            
            
    def start_server():
        server_host = '127.0.0.1'
        server_port = 8080
        httpd = SocketServer.TCPServer((server_host,server_port), MyHttpHandler)
        logging.info('
    Start server success ... 
    server_host:'+server_host+'   server_port:'+str(server_port))
        print('exe_server started on '+str(server_host)+' server_port:'+str(server_port))
        httpd.serve_forever()
    
    if __name__ == "__main__":
        start_server()

    python3与python2中SimpleHTTPRequestHandler导入方式不同,3是 from http.server import SimpleHTTPRequestHandler  , 2是 from SimpleHTTPServer import SimpleHTTPRequestHandler  ;

     另外serversocket也不一样3是 import socketserver httpd = socketserver.TCPServer((server_host,server_port), MyHttpHandler) ,2是 import SocketServer httpd = SocketServer.TCPServer((server_host,server_port), MyHttpHandler) 

    其他变化可自行设置.......

  • 相关阅读:
    6-2 播放厅模块基础环境构建
    6-1 Eureka实战之播放厅模块章节介绍
    5-18 影片模块作业思路讲解
    5-17 影院模块表现层构建
    5-16 影院模块基础环境构建
    5-15 影院模块表结构介绍
    5-14 影片模块整体测试
    5-13 影片保存实现
    5-12 影片保存准备
    5-11 影片详情查询实现
  • 原文地址:https://www.cnblogs.com/xjh713/p/10021919.html
Copyright © 2020-2023  润新知