Python基于ThreadingTCPServer创建多线程代理的方法示例

yipeiwu_com5年前Python基础

本文实例讲述了Python基于ThreadingTCPServer创建多线程代理的方法。分享给大家供大家参考,具体如下:

#coding=utf8
from BaseHTTPServer import BaseHTTPRequestHandler
from SocketServer import ThreadingTCPServer
import gzip
from StringIO import StringIO
import logging
logging.basicConfig(level=logging.DEBUG,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename='proxy.log',
        filemode='w')
class proxyHandler(BaseHTTPRequestHandler):
  def do_POST(self):
    while True:
      try:
        path = self.path
        if path.split("/")[-1] =="statistics":
          #获取post提交的数据
          datas =gzip.GzipFile(fileobj=StringIO(self.rfile.read())).read()
          self.wfile.write(datas)
          logging.debug(datas)
          print datas
      except Exception,e:
        logging.error(e)
      finally:
        self.finish()
  def do_CONNECT(self):
    pass
  def do_GET(self):
    pass
def test():
  host='127.0.0.1'
  port=8888
  try:
    server = ThreadingTCPServer((host, port), proxyHandler)
    print 'Welcome to the Server HTTP On %s Port %d...' %(host,port)
    server.serve_forever()
  except KeyboardInterrupt,e:
    logging.error(e)
    #print '^C received, shutting down server'
    server.socket.close()
if __name__ == '__main__':
  test()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python检测QQ在线状态的方法

本文实例讲述了Python检测QQ在线状态的方法。分享给大家供大家参考。具体实现方法如下: import time,datetime import urllib2 def ch...

python通过配置文件共享全局变量的实例

在使用Python编写的应用的过程中,有时会遇到多个文件之间传递同一个全局变量的情况,此时通过配置文件定义全局变量是一个比较好的选择。 首先配置config.py模块,config需要设...

值得收藏的10道python 面试题

值得收藏的10道python 面试题

Q1:PEP8是什么?Python之禅(import this)是什么? 这题是考察你对编码规范的认识,无论是自己写代码还是在团队中写代码,了解并遵循代码规范是很基础的要求。企业中在提交...

利用Python如何生成随机密码

本位实例为大家分享了Python生成随机密码的实现过程,供大家参考,具体内容如下 写了个程序,主要是用来检测MySQL数据库的空密码和弱密码的, 在这里,定义了三类弱密码: 1. 连续数...

解决python3 HTMLTestRunner测试报告中文乱码的问题

使用HTMLTestRunner输出的测试报告中,标题和错误说明的中文乱码。 环境: python v3.6 HTMLTestRunner v0.8.2 定位问题 刚开始以为是pytho...