htlogr.py 2.3KB

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