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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

树莓派与PC端在局域网内运用python实现即时通讯

电脑和树莓派在同一局域网内,先在电脑和树莓派创建python运行环境,然后在树莓派中用python运行rpi.py;在电脑上运行computer.py;电脑上输入字符即可在树莓派上即时显...

实例详解python函数的对象、函数嵌套、名称空间和作用域

函数的对象 python中一切皆对象 函数对象的四大功能 引用 def f1(): print('from f1') f1() #调用函数 print(f1) print('*'...

numpy.transpose()实现数组的转置例子

说到转置操作,顺便提及矩阵与数组的区别: 矩阵:数学里的概念,其元素只能是数值,这也是区别于数组的根本所在 数组:计算机中的概念,代表一种数据组织、存储方式,其元素可以是数字、也可以是字...

python使用logging模块发送邮件代码示例

logging模块不只是能记录log,还能发送邮件,使用起来非常简单方便 #coding=utf-8 ''''' Created on 2016-3-21 @author:...

详解Pytorch 使用Pytorch拟合多项式(多项式回归)

详解Pytorch 使用Pytorch拟合多项式(多项式回归)

使用Pytorch来编写神经网络具有很多优势,比起Tensorflow,我认为Pytorch更加简单,结构更加清晰。 希望通过实战几个Pytorch的例子,让大家熟悉Pytorch的使用...