使用proxpy确定哪个响应属于哪个请求

时间:2015-01-27 07:48:02

标签: python http proxy http-proxy

我正在为proxpy写一个插件(你不需要熟悉它来回答这个问题)。这基本上是HTTP / HTTPS代理。您可以通过实现两个函数来扩展它,其中的参数分别是HTTP请求和响应。像这样:

method1(request):  
    #your implementation

method2(response):  
    #your implementation

我想以下列格式简单地将请求和响应写入文件。

Request 1  
Response of request 1  
Request 2  
Response of request 2.  
#etc

但是,请求和响应可能不一定按顺序排列,因此它们的写法如下:

Request 1  
Request 2  
Response of request 2  
Request 3  
Response of request 3  
Response of request 2  

因此,实质上,我想要做的是找出每个响应对应的请求。

1 个答案:

答案 0 :(得分:3)

您可以尝试类似下面的代码,将每个请求存储在由线程ID键入的字典中,然后使用相同的线程ID匹配响应。这依赖于proxpy为每个请求和响应对使用单独的工作线程这一事实(需要了解proxpy实现的内容!)。

请注意,在插件代码之外引发的异常将导致"孤立"请求sent字典中的请求,但如果重用线程ID(在实践中观察到的话),这可能不是一个问题。

此外,此插件的输出将记录配对的请求和响应,但顺序将是接收响应的顺序,而不一定是发送的顺序。

import threading

lock = threading.Lock()
sent = {}
req_seq = 0

def proxy_mangle_request(req):
    global req_seq
    lock.acquire()
    req_seq += 1
    thread_id = threading.current_thread().ident
#    print "thread id = {}".format(thread_id)
    req.seq = req_seq
    sent[thread_id] = req
    lock.release()

    return req

def proxy_mangle_response(res):
    thread_id = threading.current_thread().ident
#    print "Got response for thread_id {}".format(thread_id)
    print "Request: {}".format(sent[thread_id].seq)
    lock.acquire()
    del sent[thread_id]
    lock.release()

    print "Response: {}".format(res)
    return res
相关问题