3 """Example of rate-limiting your web server.
5 Caveat emptor: While the transfer rates imposed by this mechanism will
6 look accurate with wget's rate-meter, don't forget to examine your network
7 interface's traffic statistics as well. The current implementation tends
8 to create lots of small packets in some conditions, and each packet carries
9 with it some bytes of overhead. Check to make sure this overhead is not
10 costing you more bandwidth than you are saving by limiting the rate!
13 from twisted.protocols import htb
17 serverFilter = htb.HierarchicalBucketFilter()
18 serverBucket = htb.Bucket()
20 # Cap total server traffic at 20 kB/s
21 serverBucket.maxburst = 20000
22 serverBucket.rate = 20000
24 serverFilter.buckets[None] = serverBucket
26 # Web service is also limited per-host:
27 class WebClientBucket(htb.Bucket):
28 # Your first 10k is free
30 # One kB/s thereafter.
33 webFilter = htb.FilterByHost(serverFilter)
34 webFilter.bucketFactory = shaper.WebClientBucket
36 servertype = "web" # "chargen"
38 if servertype == "web":
39 from twisted.web import server, static
40 site = server.Site(static.File("/var/www"))
41 site.protocol = htb.ShapedProtocolFactory(site.protocol, webFilter)
42 elif servertype == "chargen":
43 from twisted.protocols import wire
44 from twisted.internet import protocol
46 site = protocol.ServerFactory()
47 site.protocol = htb.ShapedProtocolFactory(wire.Chargen, webFilter)
48 #site.protocol = wire.Chargen
50 from twisted.internet import reactor
51 reactor.listenTCP(8000, site)