File: benchserver.py

package info (click to toggle)
python-scrapy 1.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 4,468 kB
  • ctags: 4,468
  • sloc: python: 22,154; xml: 199; makefile: 76; sh: 3
file content (44 lines) | stat: -rw-r--r-- 1,312 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import random
from six.moves.urllib.parse import urlencode
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor


class Root(Resource):

    isLeaf = True

    def getChild(self, name, request):
        return self

    def render(self, request):
        total = _getarg(request, 'total', 100, int)
        show = _getarg(request, 'show', 10, int)
        nlist = [random.randint(1, total) for _ in range(show)]
        request.write("<html><head></head><body>")
        args = request.args.copy()
        for nl in nlist:
            args['n'] = nl
            argstr = urlencode(args, doseq=True)
            request.write("<a href='/follow?{0}'>follow {1}</a><br>"
                          .format(argstr, nl))
        request.write("</body></html>")
        return ''


def _getarg(request, name, default=None, type=str):
    return type(request.args[name][0]) \
        if name in request.args else default


if __name__ == '__main__':
    root = Root()
    factory = Site(root)
    httpPort = reactor.listenTCP(8998, Site(root))

    def _print_listening():
        httpHost = httpPort.getHost()
        print("Bench server at http://{}:{}".format(httpHost.host, httpHost.port))
    reactor.callWhenRunning(_print_listening)
    reactor.run()