File: access.py

package info (click to toggle)
python-daphne 4.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 392 kB
  • sloc: python: 2,593; makefile: 28
file content (70 lines) | stat: -rw-r--r-- 2,389 bytes parent folder | download | duplicates (3)
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
60
61
62
63
64
65
66
67
68
69
70
import datetime


class AccessLogGenerator:
    """
    Object that implements the Daphne "action logger" internal interface in
    order to provide an access log in something resembling NCSA format.
    """

    def __init__(self, stream):
        self.stream = stream

    def __call__(self, protocol, action, details):
        """
        Called when an action happens; use it to generate log entries.
        """
        # HTTP requests
        if protocol == "http" and action == "complete":
            self.write_entry(
                host=details["client"],
                date=datetime.datetime.now(),
                request="%(method)s %(path)s" % details,
                status=details["status"],
                length=details["size"],
            )
        # Websocket requests
        elif protocol == "websocket" and action == "connecting":
            self.write_entry(
                host=details["client"],
                date=datetime.datetime.now(),
                request="WSCONNECTING %(path)s" % details,
            )
        elif protocol == "websocket" and action == "rejected":
            self.write_entry(
                host=details["client"],
                date=datetime.datetime.now(),
                request="WSREJECT %(path)s" % details,
            )
        elif protocol == "websocket" and action == "connected":
            self.write_entry(
                host=details["client"],
                date=datetime.datetime.now(),
                request="WSCONNECT %(path)s" % details,
            )
        elif protocol == "websocket" and action == "disconnected":
            self.write_entry(
                host=details["client"],
                date=datetime.datetime.now(),
                request="WSDISCONNECT %(path)s" % details,
            )

    def write_entry(
        self, host, date, request, status=None, length=None, ident=None, user=None
    ):
        """
        Writes an NCSA-style entry to the log file (some liberty is taken with
        what the entries are for non-HTTP)
        """
        self.stream.write(
            '%s %s %s [%s] "%s" %s %s\n'
            % (
                host,
                ident or "-",
                user or "-",
                date.strftime("%d/%b/%Y:%H:%M:%S"),
                request,
                status or "-",
                length or "-",
            )
        )