How to detect HTTP request in python + twisted?

I am learning network programming using twisted 10 in python. In the code below, is there a way to detect an HTTP request when receiving data? also get the domain name, subdomain, port value from this? Discard it if its not http data?

from twisted.internet import stdio, reactor, protocol

from twisted.protocols import basic

import re



class DataForwardingProtocol(protocol.Protocol):

    def _ _init_ _(self):

        self.output = None

        self.normalizeNewlines = False



    def dataReceived(self, data):

        if self.normalizeNewlines:

            data = re.sub(r"(\r\n|\n)", "\r\n", data)

        if self.output:

            self.output.write(data)



class StdioProxyProtocol(DataForwardingProtocol):

    def connectionMade(self):

        inputForwarder = DataForwardingProtocol( )

        inputForwarder.output = self.transport

        inputForwarder.normalizeNewlines = True

        stdioWrapper = stdio.StandardIO(inputForwarder)

        self.output = stdioWrapper

        print "Connected to server.  Press ctrl-C to close connection."



class StdioProxyFactory(protocol.ClientFactory):

    protocol = StdioProxyProtocol



    def clientConnectionLost(self, transport, reason):

        reactor.stop( )



    def clientConnectionFailed(self, transport, reason):

        print reason.getErrorMessage( )

        reactor.stop( )



if __name__ == '_ _main_ _':

    import sys

    if not len(sys.argv) == 3:

        print "Usage: %s host port" % _ _file_ _

        sys.exit(1)



    reactor.connectTCP(sys.argv[1], int(sys.argv[2]), StdioProxyFactory( ))

    reactor.run( )
+3
source share
2 answers

protocol.dataReceived , which you redefine, is too low-level to serve for this purpose without smart buffering, I do not - in the documents that I just quoted,

Called when data is received.

. .

data

. , , , , , ( ! , , , .

, .

LineReceiver.lineReceived ( protocols.basic.LineReceiver, ), , HTTP- "" - , , :

, , .

, / ( twisted.web, . , ),

, , ?

Host (cfr RFC, 14.23) , .

+3

, , , : http://twistedmatrix.com/documents/10.0.0/api/twisted.web.proxy.html

HTTP-. , . , . , HTTP Protocol Proxy, . , .

+1

Source: https://habr.com/ru/post/1758525/


All Articles