python - 手动给扭曲(Web)网络堆栈一个数据包来处理?

标签 python twisted

我正在使用twisted 框架运行HTTP 服务器。有什么方法可以“手动”要求它处理一些有效负载吗?例如,如果我构建了一些以太网帧,我可以要求twisted的reactor来处理它,就像它刚刚到达我的网卡一样吗?

最佳答案

你可以这样做:

from twisted.web import server
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, ClientFactory

class SomeWebThing(Resource):
    def render_GET(self, request):
        return "hello\n"

class SomeClient(Protocol):
    def dataReceived(self, data):
        p = self.factory.site.buildProtocol(self.transport.addr)
        p.transport = self.transport
        p.dataReceived(data)

class SomeClientFactory(ClientFactory):
    protocol = SomeClient
    def __init__(self, site):
        self.site = site

if __name__ == '__main__':
    root = Resource()
    root.putChild('thing', SomeWebThing())
    site = server.Site(root)
    reactor.listenTCP(8000, site)

    factory = SomeClientFactory(site)
    reactor.connectTCP('localhost', 9000, factory)

    reactor.run()

并将其保存为 simpleinjecter.py,如果您随后这样做(从命令行):

echo -e "GET /thing HTTP/1.1\r\n\r\n" | nc -l 9000  # runs a server, ready to send req to first client connection
python simpleinjecter.py

它应该按预期工作,端口 9000 上的 nc 服务器发出的请求作为有效负载传输到扭曲的 Web 服务器,并且响应按预期返回。

关键行位于 SomeClient.dataRecieved() 中。您需要一个具有正确方法的传输对象——在上面的示例中,我只是从客户端连接中窃取该对象。如果您不打算这样做,我想您将不得不制作一个,因为堆栈将需要执行诸如调用 getPeer() 之类的操作。

关于python - 手动给扭曲(Web)网络堆栈一个数据包来处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1546745/

相关文章:

python - maybeDeferred 模拟与 asyncio

python - 使用 Celery 作为 Twisted 应用程序的控制 channel

python - Scrapy:如何从其他 python 脚本运行 spider 两次或更多次?

python - Twisted:在互联网连接断开时捕获 DNSLookupError

python - 如何根据 pandas 的第二列删除重复项?

python - 属性错误 : 'module' object has no attribute 'DefaultRoutingSearchParameters'

python - 为什么 schema_translate_map 不更改架构?

python - 根据距某个点的距离从列表中随机选择一个项目?

python - 如何通过给出多个元组来获取一个 django 查询集

python - 将图像插入 pdf 文件