Skip to content

denismakogon/hotfn-py

Repository files navigation

Build Status

HTTP over STDIN/STDOUT lib parser

Purpose of this library to provide simple interface to parse HTTP 1.1 requests represented as string

Following examples are showing how to use API of this library to work with streaming HTTP requests from Fn service.

Handling Hot HTTP Functions

A main loop is supplied that can repeatedly call a user function with a series of HTTP requests. In order to utilise this, you can write your app.py as follows:

from hotfn.http import worker
from hotfn.http import response


def app(context, **kwargs):
    body = kwargs.get('data')
    return response.RawResponse(context.version, 200, "OK", body.readall())


if __name__ == "__main__":
    worker.run(app)

Automatic HTTP input coercions

Decorators are provided that will attempt to coerce input values to Python types. Some attempt is made to coerce return values from these functions also:

from hotfn.http import worker


@worker.coerce_input_to_content_type
def app(context, **kwargs):
    """
    body is a request body, it's type depends on content type
    """
    return kwargs.get('data')


if __name__ == "__main__":
    worker.run(app)

Working with async automatic HTTP input coercions

Latest version (from 0.0.6) supports async coroutines as a request body processors:

import asyncio

from hotfn.http import worker
from hotfn.http import response


@worker.coerce_input_to_content_type
async def app(context, **kwargs):
    headers = {
        "Content-Type": "plain/text",
    }
    return response.RawResponse(
        context.version, 200, "OK",
        http_headers=headers,
        response_data="OK")


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    worker.run(app, loop=loop)

Handling Hot JSON Functions

A main loop is supplied that can repeatedly call a user function with a series of JSON requests. In order to utilise this, you can write your app.py as follows:

from hotfn.json import worker


def handler(context, data=None, loop=None):
    return data


if __name__ == "__main__":
    worker.run(handler)

Working with async Hot JSON Functions

Latest version (from 0.0.6) supports async coroutines as a request body processors:

import asyncio

from hotfn.json import worker


async def handler(context, data=None, loop=None):
    return data


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    worker.run(handler, loop=loop)

As you can see app function is no longer callable, because its type: coroutine, so we need to bypass event loop inside