htlogr.py 2.1KB

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