2011-06-27 10 views
9

Tôi muốn viết một proxy đơn giản làm xáo trộn văn bản trong phần nội dung của các trang được yêu cầu. Tôi đã đọc các phần của tài liệu xoắn và một số câu hỏi tương tự khác ở đây trên stackoverflow nhưng tôi là một chút của một noob vì vậy tôi vẫn không nhận được nó.Cần trợ giúp viết một proxy bị xoắn

Đây là những gì tôi có bây giờ, tôi không biết làm thế nào để truy cập và sửa đổi các trang

from twisted.web import proxy, http 
from twisted.internet import protocol, reactor 
from twisted.python import log 
import sys 

log.startLogging(sys.stdout) 

class ProxyProtocol(http.HTTPChannel): 
    requestFactory = PageHandler 

class ProxyFactory(http.HTTPFactory): 
    protocol = ProxyProtocol 

if __name__ == '__main__': 
    reactor.listenTCP(8080, ProxyFactory()) 
    reactor.run() 

bạn có thể vui lòng giúp tôi ra? Tôi đánh giá cao một ví dụ đơn giản (ví dụ: thêm nội dung nào đó vào nội dung v.v.).

Trả lời

6

Điều tôi làm là triển khai ProxyClient mới, nơi tôi sửa đổi dữ liệu sau khi tôi tải xuống từ máy chủ web và trước khi tôi gửi nó tới trình duyệt web.

from twisted.web import proxy, http 
class MyProxyClient(proxy.ProxyClient): 
def __init__(self,*args,**kwargs): 
    self.buffer = "" 
    proxy.ProxyClient.__init__(self,*args,**kwargs) 
def handleResponsePart(self, buffer): 
    # Here you will get the data retrieved from the web server 
    # In this example, we will buffer the page while we shuffle it. 
    self.buffer = buffer + self.buffer 
def handleResponseEnd(self): 
    if not self._finished: 
    # We might have increased or decreased the page size. Since we have not written 
    # to the client yet, we can still modify the headers. 
    self.father.responseHeaders.setRawHeaders("content-length", [len(self.buffer)]) 
    self.father.write(self.buffer) 
    proxy.ProxyClient.handleResponseEnd(self) 

class MyProxyClientFactory(proxy.ProxyClientFactory): 
protocol = MyProxyClient 

class ProxyRequest(proxy.ProxyRequest): 
protocols = {'http': MyProxyClientFactory} 
ports = {'http': 80 } 
def process(self): 
    proxy.ProxyRequest.process(self) 

class MyProxy(http.HTTPChannel): 
requestFactory = ProxyRequest 

class ProxyFactory(http.HTTPFactory): 
protocol = MyProxy 

Hy vọng điều này cũng phù hợp với bạn.

+0

Khi yêu cầu proxy của tôi nhận được phản hồi lỗi 404, tôi nhận được lỗi "Lỗi không khớp trong Trì hoãn: Lỗi: twisted.web.error.Error: 404 Not Found". Làm cách nào để tôi gặp lỗi này? –