doc: Fixed typo.
[ashd.git] / python3 / ashd / perf.py
CommitLineData
d5ee5cde
FT
1import collections
2try:
3 import pdm.perf
4except:
5 pdm = None
6
7reqstat = {}
8
9if pdm:
10 statistics = pdm.perf.staticdir()
11 statistics["req"] = pdm.perf.valueattr(reqstat)
12 requests = pdm.perf.eventobj()
13
14 class reqstart(pdm.perf.startevent):
15 def __init__(self, env):
8dbc4786 16 super().__init__()
d5ee5cde
FT
17 self.method = env.get("REQUEST_METHOD")
18 self.uri = env.get("REQUEST_URI")
19 self.host = env.get("HTTP_HOST")
44f2a2fe
FT
20 self.remoteaddr = env.get("REMOTE_ADDR")
21 self.remoteport = env.get("REMOTE_PORT")
d5ee5cde
FT
22
23 class reqfinish(pdm.perf.finishevent):
24 def __init__(self, start, aborted, status):
8dbc4786 25 super().__init__(start, aborted)
d5ee5cde
FT
26 self.status = status
27
28class request(object):
29 def __init__(self, env):
30 self.resp = None
31 if pdm:
32 self.startev = reqstart(env)
33 requests.notify(self.startev)
34
35 def response(self, resp):
36 self.resp = resp
37
38 def finish(self, aborted):
39 key = None
40 status = None
41 try:
42 if len(self.resp) > 0:
43 status = self.resp[0]
44 if isinstance(status, collections.ByteString):
45 status = status.decode("latin-1")
46 else:
47 status = str(status)
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