Handlers: rendering mixin
[breadcrumb.git] / code / breadcrumb / server / handlers / http.py
blob0223b6040ece677acc1c896963a93402887f858d
1 # -*- coding: utf8 -*-
2 """ HTTP handler code for Breadcrumb servers. """
4 # Copyright (C) 2008 Laurens Van Houtven <lvh at laurensvh.be>
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.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 import urllib
19 import httplib
20 import logging
21 import time
23 from common import PointQueueHandler, Renderer
25 class HTTPHandler(PointQueueHandler, Renderer):
26 """A handler for sending data over HTTP.
28 ``action`` and ``name`` mean the same thing as in an HTML form. This is
29 illustrated by the following example:
31 To POST something to a server for which the URL looks like this::
33 http://test.example:8080/my_cgi_app
35 ... and the element looks something like this::
37 <input name="foo" action="/my_cgi_app" method='POST' />
39 you would create a handler instance like this::
41 HTTPHandler(host = "text.example",
42 port = 8080,
43 action = "/my_cgi_app",
44 name = "foo")
46 We don't need to pass the method here, because POST is the default. You can
47 use any string httplib understands (``GET``, for example.).
49 This handler opens a new HTTP connection for each submission.
50 """
51 def __init__(self, host = "localhost", port = 80,
52 action = None, name = None, method = 'POST',
53 threshold = 1, rendertype = None):
54 PointQueueHandler.__init__(self, threshold = threshold)
55 Renderer.__init__(self, type = rendertype)
57 if not all([action, name, method]):
58 raise RuntimeError, 'not enough parameters for HTTPHandler'
59 else:
60 self.action, self.element, self.method = action, name, method
62 self.host, self.port = str(host), int(port)
63 self.headers = {}
65 for identifier in ['\x30, \x31']:
66 self.identifiers.add(identifier)
68 logging.debug("Initialized HTTPHandler at %s:%s" % (host, port))
70 def send(self, outstr):
71 """Sends the given string across HTTP."""
72 parameters = urllib.urlencode({self.element: outstr})
74 connection = httplib.HTTPConnection("%s:%d" % (self.host, self.port))
75 connection.request(self.method, self.action, parameters, self.headers)
76 connection.close()