python3 使用时如下:

  1. #!/usr/bin/env python3
  2. #coding=utf-8
  3. from http.server import SimpleHTTPRequestHandler
  4. import socketserver
  5. import os,io,shutil
  6. import logging
  7. import cgi
  8. import sys
  9. import json
  10.  
  11. log_path = './logs/run_server_logs.log'
  12. 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)
  13. class MyHttpHandler(SimpleHTTPRequestHandler):
  14.  
  15. def _set_headers(self):
  16. self.send_response(200)
  17. self.send_header('Content-type', 'text/html')
  18. self.end_headers()
  19.  
  20. def send_datas(self,contents):
  21. #指定返回编码
  22. enc = "UTF-8"
  23. content = contents.encode(enc)
  24. f = io.BytesIO()
  25. f.write(content)
  26. f.seek(0)
  27. self.send_response(200)
  28. self.send_header("Content-type", "text/html; charset=%s" % enc)
  29. self.send_header("Content-Length", str(len(contents)))
  30. self.end_headers()
  31. shutil.copyfileobj(f,self.wfile)
  32.  
  33. def do_GET(self):
  34. logging.info("got get request "+str(self.path))
  35. values = str(self.path)
  36. self.send_datas('这是get请求'+values)
  37.  
  38. def do_POST(self):
  39. logging.info("got post!!")
  40. datasets = cgi.FieldStorage(fp = self.rfile,headers = self.headers,environ = {'REQUEST_METHOD': 'POST'})
  41. logging.info(str(datasets))
  42. id = datasets.getvalue('id')
  43. name = datasets.getvalue('name')
  44. msg = "name=="+str(name)+" id=="+str(id)
  45. flag = 1
  46. results = {"status":flag,"msg":msg}
  47. self.send_datas(json.dumps(results))
  48.  
  49. def start_server():
  50. server_host = '127.0.0.1'
  51. server_port = 8080
  52. httpd = socketserver.TCPServer((server_host,server_port), MyHttpHandler)
  53. logging.info('\nStart server success ... \nserver_host:'+server_host+' server_port:'+str(server_port))
  54. print('exe_server started on '+str(server_host)+' server_port:'+str(server_port))
  55. httpd.serve_forever()
  56.  
  57. if __name__ == "__main__":
  58. start_server()

python2使用时:

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. from SimpleHTTPServer import SimpleHTTPRequestHandler
  4. import SocketServer
  5. import os,io,shutil
  6. import logging
  7. import cgi
  8. import urlparse
  9. import sys
  10. reload(sys)
  11. sys.setdefaultencoding('utf-8')
  12.  
  13. log_path = './logs/run_server_logs.log'
  14. 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)
  15. class MyHttpHandler(SimpleHTTPRequestHandler):
  16.  
  17. def _set_headers(self):
  18. self.send_response(200)
  19. self.send_header('Content-type', 'text/html')
  20. self.end_headers()
  21.  
  22. def send_datas(self,contents):
  23. #指定返回编码
  24. enc = "UTF-8"
  25. #contents = contents.encode(enc)
  26. f = io.BytesIO()
  27. f.write(contents)
  28. f.seek(0)
  29. self.send_response(200)
  30. self.send_header("Content-type", "text/html; charset=%s" % enc)
  31. self.send_header("Content-Length", str(len(contents)))
  32. self.end_headers()
  33. shutil.copyfileobj(f,self.wfile)
  34.  
  35. def do_GET(self):
  36. logging.info("got get request "+str(self.path))
  37. values = str(self.path)
  38. self.send_datas('get请求方式'+values)
  39.  
  40. def do_POST(self):
  41. logging.info("got post!!")
  42. datasets = cgi.FieldStorage(fp = self.rfile,headers = self.headers,environ = {'REQUEST_METHOD': 'POST'})
  43. logging.info(str(datasets))
  44. id = datasets.getvalue('id')
  45. name = datasets.getvalue('name')
  46.  
  47. msg = "name=="+str(name)+" id=="+str(id)
  48. flag = 1
  49. results = {'status':flag,'msg':msg}
  50. self.send_datas(str(results))
  51.  
  52. def start_server():
  53. server_host = '127.0.0.1'
  54. server_port = 8080
  55. httpd = SocketServer.TCPServer((server_host,server_port), MyHttpHandler)
  56. logging.info('\nStart server success ... \nserver_host:'+server_host+' server_port:'+str(server_port))
  57. print('exe_server started on '+str(server_host)+' server_port:'+str(server_port))
  58. httpd.serve_forever()
  59.  
  60. if __name__ == "__main__":
  61. 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)

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

python3与python2使用python原生SimpleHTTPRequestHandler的更多相关文章

  1. Win10下python3和python2同时安装并解决pip共存问题

    特别说明,本文是在Windows64位系统下进行的,32位系统请下载相应版本的安装包,安装方法类似. 使用python开发,环境有Python2和 python3 两种,有时候需要两种环境切换使用,下 ...

  2. 【转】Win10下 python3和python2同时安装并解决pip共存问题

    1.下载python3和python2 进入python官网,链接https://www.python.org/ 选择Downloads--->Windows,点击进入就可以看到寻找想要的pyt ...

  3. 【转】Win10下python3和python2多版本同时安装并解决pip共存问题

    [转]Win10下python3和python2多版本同时安装并解决pip共存问题 特别说明,本文是在Windows64位系统下进行的,32位系统请下载相应版本的安装包,安装方法类似. 使用pytho ...

  4. Windows同时安装python3和python2

    Windows同时安装python3和python2 https://www.cnblogs.com/shanhua-fu/p/6912683.html Windows7 下python3和pytho ...

  5. Windows7 下python3和python2同时 安装python3和python2

    1.下载python3和python2 进入python官网,链接https://www.python.org/ 选择Downloads--->Windows,点击进入就可以看到寻找想要的pyt ...

  6. Windows下python3和python2同时安装python2.exe、python3.exe和pip2、pip3设置

    1.添加python2到系统环境变量 打开,控制面板\系统和安全\系统,选择高级系统设置,环境变量,选择Path,点击编辑,新建,分别添加D:\Python\python27和D:\Python\py ...

  7. 从零开始学习PYTHON3讲义(一)认识Python

    课程名称 从零开始PYTHON3 课程长度 15讲 适用年龄 15-20岁(初三-大一) 本讲名称 认识Python 时长 90分钟 教学内容分析 Python是时下最流行的计算机编程语言之一.本课程 ...

  8. 一、Windows10下python3和python2同时安装

    python2.exe.python3.exe和pip2.pip3设置 说明:安装安装python3和python2请参考本系列教程(一) 1.添加python2到系统环境变量 打开,控制面板\系统和 ...

  9. ubuntu python3和python2切换脚本

    最近在ubuntu上开发较多,有些工具只能在python2运行,而开发又是在python3上做的开发,所以写个脚本方便在python2和python3之间切换. 切换成python2的文件usepy2 ...

随机推荐

  1. SVN 远程访问

    第一种方法 https://www.cnblogs.com/Leo_wl/p/3475167.html#_label0 默认协议为:https 端口号:443 服务器地址:https://主机名/sv ...

  2. unity StrangeIoc

    已经很久没有写博客,主要原因还是自我荒废了太久,在学习上失去了动力.最近来新的公司实习,以前都是做项目的开发,现在被调到框架组,主要从事的是框架维护还有开发.学习了许多新的知识还有优秀的框架,今天就写 ...

  3. PyQt5--Position

    # -*- coding:utf-8 -*- ''' Created on Sep 13, 2018 @author: SaShuangYiBing ''' import sys from PyQt5 ...

  4. node学习笔记_01 环境搭建

    一.下载安装nvm (node版本管理器),方便以后版本切换 nvm list            -> 查看node版本(版本最好在8.0以上,不然在vsCode断点调试进不去,跟node版 ...

  5. CVE-2017-8046(Spring Data Rest RCE)

    环境搭建参考第一个链接,springboot启动文件如下,不同的启类,将Application.class修改一下就可以了,直接debug.注意:默认版本是2.0.3版本,修改成低版本,看一下mvn下 ...

  6. 8.UDP协议

    传输层协议:TCP UDP TCP和UDP有什么区别? TCP是面向连接的 UDP是面向无连接.在互通之前,面向连接的协议会先建立连接,如TCP会三次握手.所谓的建立连接,是为了在客户端和服务端维护连 ...

  7. lsof |grep deleted;du -sh / ;df -h;

    有台机器磁盘满了: 进程端口都正常,存活:但是页面却完全打不开了: 日志爆满:删除日志后: 在根上 du -sh * 然后 df -h 发现差别太大了: du -sh * / 才不足7G: df -h ...

  8. testNG参数化

    听说testNG比junit更好用,记录下 环境:springboot2.0+testNG6.8+maven+myeclipse 一 安装 (1)m'yeclipse安装testNg包,下载testN ...

  9. 使用Java线程并发库实现两个线程交替打印的线程题

    背景:是这样的今天在地铁上浏览了以下网页,看到网上一朋友问了一个多线程的问题.晚上闲着没事就决定把它实现出来. 题目: 1.开启两个线程,一个线程打印A-Z,两一个线程打印1-52的数据. 2.实现交 ...

  10. python:'ascii' codec can't encode character

    python默认的编码是ascii,当程序中出现非ascii编码时,python的处理常常会报这样的错,python没办法处理非ascii编码的, 此时需要自己设置python的默认编码,一般设置为u ...