1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. self.last_error = None
  36. def _zipup_params(self, params):
  37. args = []
  38. for name, value in params.iteritems():
  39. if params[name]:
  40. value = str(value)
  41. args.append("%s=%s" % (name, urllib.quote(value)))
  42. return "&".join(args)
  43. def _serialize(self, data):
  44. fields = []
  45. for key in sorted(data.keys()):
  46. value = data[key]
  47. fields.append("%s%s%s" % (key, self.DIV_VALUE, value))
  48. return self.DIV_FIELD.join(fields)
  49. def log(self, msg, tag=None, i=None):
  50. params = {"msg": msg, "tag": tag, "i": i}
  51. pq = "%s?%s" % (self.parsed_url.path, self._zipup_params(params))
  52. self.conn.request("GET", pq)
  53. self.last_error = None
  54. return_msg = None
  55. try:
  56. r = self.conn.getresponse()
  57. assert r.status == 200, ("logging server returned error %s,"
  58. "message not logged" % r.status)
  59. return_msg = r.read()
  60. except httplib.BadStatusLine as e:
  61. return_msg = ("httplib does not like this line:\n\n %s"
  62. % e.line)
  63. self.last_error = return_msg
  64. return return_msg
  65. def data(self, data, tag=None, i=None):
  66. assert isinstance(data, dict), "data must be dict"
  67. msg = self._serialize(data)
  68. return self.log(msg, tag=tag, i=i)