File: httpd.py

package info (click to toggle)
bro 2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 78,640 kB
  • sloc: ansic: 126,302; cpp: 95,205; yacc: 2,528; lex: 1,819; sh: 793; python: 700; makefile: 134
file content (59 lines) | stat: -rwxr-xr-x 1,774 bytes parent folder | download | duplicates (2)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#! /usr/bin/env python

try:
    # Python 2
    import BaseHTTPServer
except ImportError:
    # Python 3
    import http.server as BaseHTTPServer

class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()

        if "/empty" in self.path:
            self.wfile.write(b"")
        else:
            self.wfile.write(b"It works!")

    def do_POST(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()

        if "/empty" in self.path:
            self.wfile.write(b"")
        else:
            self.wfile.write(b"It works!")

    def version_string(self):
        return "1.0"

    def date_time_string(self):
        return "July 22, 2013"


if __name__ == "__main__":
    from optparse import OptionParser
    p = OptionParser()
    p.add_option("-a", "--addr", type="string", default="localhost",
                 help=("listen on given address (numeric IP or host name), "
                       "an empty string (the default) means INADDR_ANY"))
    p.add_option("-p", "--port", type="int", default=32123,
                 help="listen on given TCP port number")
    p.add_option("-m", "--max", type="int", default=-1,
                 help="max number of requests to respond to, -1 means no max")
    options, args = p.parse_args()

    httpd = BaseHTTPServer.HTTPServer((options.addr, options.port),
                                      MyRequestHandler)
    if options.max == -1:
        httpd.serve_forever()
    else:
        served_count = 0
        while served_count != options.max:
            httpd.handle_request()
            served_count += 1