Browse Source

Added Python version of htlogr

Alois Mahdal 11 years ago
parent
commit
9b7b9f8f71
1 changed files with 59 additions and 0 deletions
  1. 59
    0
      lib/htlogr.py

+ 59
- 0
lib/htlogr.py View File

@@ -0,0 +1,59 @@
1
+## Author: Alois Mahdal at zxcvb cz
2
+# Front-end for very primitive remote logging service. Use htlog.cgi
3
+# as back-end: put it on a HTTP server and provide URL as "path" option
4
+# when instantiating this class
5
+
6
+# This program is free software: you can redistribute it and/or modify
7
+# it under the terms of the GNU General Public License as published by
8
+# the Free Software Foundation, either version 3 of the License, or
9
+# (at your option) any later version.
10
+
11
+# This program is distributed in the hope that it will be useful,
12
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
+# GNU General Public License for more details.
15
+
16
+# You should have received a copy of the GNU General Public License
17
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
+
19
+import httplib
20
+import urlparse
21
+import urllib
22
+
23
+
24
+class htlogr:
25
+
26
+    def __init__(self, url):
27
+        self.DIV_VALUE = "="
28
+        self.DIV_FIELD = ";"
29
+        self.url = url
30
+        self.parsed_url = urlparse.urlparse(url)
31
+        self.conn = httplib.HTTPConnection(self.parsed_url.hostname)
32
+
33
+    def _zipup_params(self, params):
34
+        args = []
35
+        for name, value in params.iteritems():
36
+            if params[name]:
37
+                value = str(value)
38
+                args.append("%s=%s" % (name, urllib.quote(value)))
39
+        return "&".join(args)
40
+
41
+    def _serialize(self, data):
42
+        fields = []
43
+        for key, value in data.iteritems():
44
+            fields.append("%s%s%s" % (key, self.DIV_VALUE, value))
45
+        return self.DIV_FIELD.join(fields)
46
+
47
+    def log(self, msg, tag=None, i=None):
48
+        params = {"msg": msg, "tag": tag, "i": i}
49
+        pq = "%s?%s" % (self.parsed_url.path, self._zipup_params(params))
50
+        self.conn.request("GET", pq)
51
+        r = self.conn.getresponse()
52
+        assert r.status == 200, ("logging server returned error %s,"
53
+                                 "message not logged")
54
+        return r.read()
55
+
56
+    def data(self, data, tag=None, i=None):
57
+        assert isinstance(data, dict), "data must be dict"
58
+        msg = self._serialize(data)
59
+        return self.log(msg, tag=tag, i=i)