Imported Upstream version 12.1.0
[contrib/python-twisted.git] / doc / web / examples / logging-proxy.py
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 An example of a proxy which logs all requests processed through it.
6
7 Usage:
8     $ python logging-proxy.py
9
10 Then configure your web browser to use localhost:8080 as a proxy, and visit a
11 URL (This is not a SOCKS proxy). When browsing in this configuration, this
12 example will proxy connections from the browser to the server indicated by URLs
13 which are visited.  The client IP and the request hostname will be logged for
14 each request.
15
16 HTTP is supported.  HTTPS is not supported.
17
18 See also proxy.py for a simpler proxy example.
19 """
20
21 from twisted.internet import reactor
22 from twisted.web import proxy, http
23
24 class LoggingProxyRequest(proxy.ProxyRequest):
25     def process(self):
26         """
27         It's normal to see a blank HTTPS page. As the proxy only works
28         with the HTTP protocol.
29         """
30         print "Request from %s for %s" % (
31             self.getClientIP(), self.getAllHeaders()['host'])
32         try:
33             proxy.ProxyRequest.process(self)
34         except KeyError:
35             print "HTTPS is not supported at the moment!"
36
37 class LoggingProxy(proxy.Proxy):
38     requestFactory = LoggingProxyRequest
39
40 class LoggingProxyFactory(http.HTTPFactory):
41     def buildProtocol(self, addr):
42         return LoggingProxy()
43
44 reactor.listenTCP(8080, LoggingProxyFactory())
45 reactor.run()