doc: Fixed typo.
[ashd.git] / python / ashd / perf.py
1 try:
2     import pdm.perf
3 except:
4     pdm = None
5
6 reqstat = {}
7
8 if pdm:
9     statistics = pdm.perf.staticdir()
10     statistics["req"] = pdm.perf.valueattr(reqstat)
11     requests = pdm.perf.eventobj()
12
13     class reqstart(pdm.perf.startevent):
14         def __init__(self, env):
15             super(reqstart, self).__init__()
16             self.method = env.get("REQUEST_METHOD")
17             self.uri = env.get("REQUEST_URI")
18             self.host = env.get("HTTP_HOST")
19             self.script_uri = env.get("SCRIPT_NAME")
20             self.script_path = env.get("SCRIPT_FILENAME")
21             self.pathinfo = env.get("PATH_INFO")
22             self.querystring = env.get("QUERY_STRING")
23             self.remoteaddr = env.get("REMOTE_ADDR")
24             self.remoteport = env.get("REMOTE_PORT")
25             self.scheme = env.get("wsgi.url_scheme")
26
27     class reqfinish(pdm.perf.finishevent):
28         def __init__(self, start, aborted, status):
29             super(reqfinish, self).__init__(start, aborted)
30             self.status = status
31
32 class request(object):
33     def __init__(self, env):
34         self.resp = None
35         if pdm:
36             self.startev = reqstart(env)
37             requests.notify(self.startev)
38
39     def response(self, resp):
40         self.resp = resp
41
42     def finish(self, aborted):
43         key = None
44         status = None
45         try:
46             if len(self.resp) > 0:
47                 status = self.resp[0]
48                 p = status.find(" ")
49                 if p < 0:
50                     key = status
51                 else:
52                     key = status[:p]
53         except:
54             pass
55         reqstat[key] = reqstat.setdefault(key, 0) + 1
56         if pdm:
57             requests.notify(reqfinish(self.startev, aborted, status))
58
59     def __enter__(self):
60         return self
61     
62     def __exit__(self, *excinfo):
63         self.finish(bool(excinfo[0]))
64         return False