Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / examples / shaper.py
1 # -*- Python -*-
2
3 """Example of rate-limiting your web server.
4
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!
11 """
12
13 from twisted.protocols import htb
14 # for picklability
15 import shaper
16
17 serverFilter = htb.HierarchicalBucketFilter()
18 serverBucket = htb.Bucket()
19
20 # Cap total server traffic at 20 kB/s
21 serverBucket.maxburst = 20000
22 serverBucket.rate = 20000
23
24 serverFilter.buckets[None] = serverBucket
25
26 # Web service is also limited per-host:
27 class WebClientBucket(htb.Bucket):
28     # Your first 10k is free
29     maxburst = 10000
30     # One kB/s thereafter.
31     rate = 1000
32
33 webFilter = htb.FilterByHost(serverFilter)
34 webFilter.bucketFactory = shaper.WebClientBucket
35
36 servertype = "web" # "chargen"
37
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
45
46     site = protocol.ServerFactory()
47     site.protocol = htb.ShapedProtocolFactory(wire.Chargen, webFilter)
48     #site.protocol = wire.Chargen
49
50 from twisted.internet import reactor
51 reactor.listenTCP(8000, site)
52 reactor.run()