HTTP Service

The HTTP service is a basic servlet container, dispatching HTTP requests to the handler registered for the given path. A servlet can be a simple class or a component, registered programmatically to the HTTP service, or a service registered in the Pelix framework and automatically registered by the HTTP service.


Even if it borrows the concept of servlets from Java, the Pelix HTTP service doesn’t follow the OSGi specification. The latter inherits a lot from the existing Java APIs, while this is an uncommon way to work in Python.

The basic implementation of the HTTP service is defined in pelix.http.basic. It is based on the HTTP server available in the standard Python library (see http.server). Future implementations might appear in the future Pelix implementations, based on more robust requests handlers.

Configuration properties

All implementations of the HTTP service must support the following property:

Property Default Description
pelix.http.address The address the HTTP server is bound to
pelix.http.port 8080 The port the HTTP server is bound to


The HTTP bundle defines a component factory which name is implementation-dependent. The HTTP service factory provided by Pelix/iPOPO is pelix.http.service.basic.factory.

Here is a snippet that starts a HTTP server component, named http-server, which only accepts local clients on port 9000:

from pelix.framework import FrameworkFactory
from pelix.ipopo.constants import use_ipopo

# Start the framework
framework = FrameworkFactory.get_framework()
context = framework.get_bundle_context()

# Install & start iPOPO

# Install & start the basic HTTP service

# Instantiate a HTTP service component
with use_ipopo(context) as ipopo:
       'pelix.http.service.basic.factory', 'http-server',
       {'pelix.http.address': 'localhost',
        'pelix.http.port': 9000})

This code starts an HTTP server which will be listening on port 9000 and the HTTP service will be ready to handle requests. As no servlet service has been registered, the server will only return 404 errors.


HTTP service

The HTTP service provides the following interface:

class pelix.http.basic.HttpService

Basic HTTP service component


Retrieves the (address, port) tuple to access the server

static get_hostname()

Retrieves the server host name

Returns:The server host name

Returns the paths registered by servlets

Returns:The paths registered by servlets (sorted list)

Retrieves the servlet matching the given path and its parameters. Returns None if no servlet matches the given path.

Parameters:path – A request URI
Returns:A tuple (servlet, parameters, prefix) or None

Returns True if this is an HTTPS server

Returns:True if this server uses SSL
register_servlet(path, servlet, parameters=None)

Registers a servlet

  • path – Path handled by this servlet
  • servlet – The servlet instance
  • parameters – The parameters associated to this path

True if the servlet has been registered, False if it refused the binding.


ValueError – Invalid path or handler

unregister(path, servlet=None)

Unregisters the servlet for the given path

  • path – The path to a servlet
  • servlet – If given, unregisters all the paths handled by this servlet

True if at least one path as been unregistered, else False

The service also provides two utility methods to ease the display of error pages:

class pelix.http.basic.HttpService

Basic HTTP service component

make_exception_page(path, stack)

Prepares a page printing an exception stack trace in a 500 error

  • path – Request path
  • stack – Exception stack trace

A HTML page


Prepares a “page not found” page for a 404 error

Parameters:path – Request path
Returns:A HTML page

Servlet service

To use the whiteboard pattern, a servlet can be registered as a service providing the pelix.http.servlet specification. It must also have a valid pelix.http.path property, or it will be ignored.

The binding methods described below have a parameters argument, which represents a set of properties of the server, given as a dictionary. Some parameters can also be given when using the register_servlet() method, with the parameters argument.

In any case, the following entries must be set by all implementations of the HTTP service and can’t be overridden when register a servlet. Note that their content and liability is implementation-dependent:

  • http.address: the binding address (str) of the HTTP server;
  • http.port: the real listening port (int) of the HTTP server;
  • http.https: a boolean flag indicating if the server is listening to HTTP (False) or HTTPS (True) requests;
  • the name (str) of the server. If the server is an iPOPO component, it should be the instance name;
  • http.extra: an implementation dependent set of properties.

A servlet for the Pelix HTTP service has the following methods:

class HttpServlet

These are the methods that the HTTP service can call in a servlet. Note that it is not necessary to implement them all: the service has a default behaviour for missing methods.

accept_binding(path, parameters)

This method is called before trying to bind the servlet. If it returns False, the servlet won’t be bound to the server. This allows a servlet service to be bound to a specific server.

If this method doesn’t exist or returns None or anything else but False, the calling HTTP service will consider that the servlet accepts to be bound to it.

  • path (str) – The path of the servlet in the server
  • parameters (dict) – The parameters of the server
bound_to(path, parameters)

This method is called when the servlet is bound to a path. If it returns False or raises an Exception, the registration is aborted.

  • path (str) – The path of the servlet in the server
  • parameters (dict) – The parameters of the server
unbound_from(path, parameters)

This method is called when the servlet is bound to a path. The parameters are the ones given in accept_binding() and bound_to().

  • path (str) – The path of the servlet in the server
  • parameters (dict) – The parameters of the server
do_GET(request, response)

Each request is handled by the method call do_XXX where XXX is the name of an HTTP method (do_GET, do_POST, do_PUT, do_HEAD, ...).

If it raises an exception, the server automatically sends an HTTP 500 error page. In nominal behaviour, the method must use the response argument to send a reply to the client.


HTTP request

Each request method has a request helper argument, which implements the AbstractHTTPServletRequest abstract class.

class pelix.http.AbstractHTTPServletRequest

Abstract HTTP Servlet request helper


Returns the address of the client

Returns:A (host, port) tuple

Returns the HTTP verb (GET, POST, ...) used for the request

get_header(name, default=None)

Returns the value of a header

  • name – Header name
  • default – Default value if the header doesn’t exist

The header value or the default one


Returns a copy all headers, with a dictionary interface

Returns:A dictionary-like object

Returns the request full path

Returns:A request full path (string)

Returns the path to the servlet root

Returns:A request path (string)

Returns the request input as a file stream

Returns:A file-like input stream

Returns the servlet-relative path, i.e. after the prefix

Returns:A request path (string)

Reads all the data in the input stream

Returns:The read data

HTTP response

Each request method also has a response helper argument, which implements the AbstractHTTPServletResponse abstract class.

class pelix.http.AbstractHTTPServletResponse

HTTP Servlet response helper


Ends the headers part


Retrieves the output as a file stream. end_headers() should have been called before, except if you want to write your own headers.

Returns:A file-like output stream

Checks if the given header has already been set

Parameters:name – Header name
Returns:True if it has already been set
send_content(http_code, content, mime_type='text/html', http_message=None, content_length=-1)

Utility method to send the given content as an answer. You can still use get_wfile or write afterwards, if you forced the content length.

If content_length is negative (default), it will be computed as the length of the content; if it is positive, the given value will be used; if it is None, the content-length header won’t be sent.

  • http_code – HTTP result code
  • content – Data to be sent (must be a string)
  • mime_type – Content MIME type (content-type)
  • http_message – HTTP code description
  • content_length – Forced content length
set_header(name, value)

Sets the value of a header. This method should not be called after end_headers().

  • name – Header name
  • value – Header value
set_response(code, message=None)

Sets the response line. This method should be the first called when sending an answer.

  • code – HTTP result code
  • message – Associated message

Writes the given data. end_headers() should have been called before, except if you want to write your own headers.

Parameters:data – Data to be written

Write a servlet

This snippet shows how to write a component providing the servlet service:

from pelix.ipopo.decorators import ComponentFactory, Property, Provides, \
    Requires, Validate, Invalidate, Unbind, Bind, Instantiate

@Property('_path', 'pelix.http.path', "/servlet")
class SimpleServletFactory(object):
  Simple servlet factory
  def __init__(self):
      self._path = None

  def bound_to(self, path, params):
      Servlet bound to a path
      print('Bound to ' + path)
      return True

  def unbound_from(self, path, params):
      Servlet unbound from a path
      print('Unbound from ' + path)
      return None

  def do_GET(self, request, response):
      Handle a GET
      content = """<html>
<title>Test SimpleServlet</title>
<li>Client address: {clt_addr[0]}</li>
<li>Client port: {clt_addr[1]}</li>
<li>Host: {host}</li>
<li>Keys: {keys}</li>
                host=request.get_header('host', 0),

      response.send_content(200, content)

To test this snippet, install and start this bundle and the HTTP service bundle in a framework, then open a browser to the servlet URL. If you used the HTTP service instantiation sample, this URL should be http://localhost:9000/servlet.