htlogr.py 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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, value in data.iteritems():
  35. fields.append("%s%s%s" % (key, self.DIV_VALUE, value))
  36. return self.DIV_FIELD.join(fields)
  37. def log(self, msg, tag=None, i=None):
  38. params = {"msg": msg, "tag": tag, "i": i}
  39. pq = "%s?%s" % (self.parsed_url.path, self._zipup_params(params))
  40. self.conn.request("GET", pq)
  41. r = self.conn.getresponse()
  42. assert r.status == 200, ("logging server returned error %s,"
  43. "message not logged")
  44. return r.read()
  45. def data(self, data, tag=None, i=None):
  46. assert isinstance(data, dict), "data must be dict"
  47. msg = self._serialize(data)
  48. return self.log(msg, tag=tag, i=i)