All-in-one Python script

If you haven’t already installed API-Hour, you can follow the Installation instructions.

Let’s an API-Hour daemon that handles HTTP requests.

Create all_in_one.py file

import logging

import api_hour
import aiohttp.web
from aiohttp.web import Response

logging.basicConfig(level=logging.INFO)  # enable logging for api_hour


class Container(api_hour.Container):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Declare HTTP server
        self.servers['http'] = aiohttp.web.Application(loop=kwargs['loop'])
        self.servers['http'].ah_container = self  # keep a reference in HTTP server to Container

        # Define HTTP routes
        self.servers['http'].router.add_route('GET',
                                              '/',
                                              self.index)

    # A HTTP handler example
    # More documentation: http://aiohttp.readthedocs.org/en/latest/web.html#handler
    async def index(self, request):
        message = 'Hello World !'
        return Response(text=message)


    # Container methods
    async def start(self):
        # A coroutine called when the Container is started
        await super().start()


    async def stop(self):
        # A coroutine called when the Container is stopped
        await super().stop()


    def make_servers(self):
        # This method is used by api_hour command line to bind your HTTP server on socket
        return [self.servers['http'].make_handler(logger=self.worker.log,
                                                  keep_alive=self.worker.cfg.keepalive,
                                                  access_log=self.worker.log.access_log,
                                                  access_log_format=self.worker.cfg.access_log_format)]

How to launch

In your current folder where you wrote your script, launch:

api_hour all_in_one:Container

You’ll see:

[2015-01-12 23:17:02 +0100] [1763] [INFO] Starting gunicorn 19.1.1
[2015-01-12 23:17:02 +0100] [1763] [INFO] Listening at: http://127.0.0.1:8000 (1763)
[2015-01-12 23:17:02 +0100] [1763] [INFO] Using worker: api_hour.Worker
[2015-01-12 23:17:02 +0100] [1766] [INFO] Booting worker with pid: 1766
INFO:api_hour.container:Starting application...

Go to http://127.0.0.1:8000/ to see the result of your index handler.

Benchmark the difference with several workers

To use several workers:

api_hour -w 16 all_in_one:Container

Compare the difference between one worker and several workers with wrk:

wrk -t12 -c400 -d30s http://127.0.0.1:8000/