How to use the tomodachi.service function in tomodachi

To help you get started, we’ve selected a few tomodachi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kalaspuff / tomodachi / tests / services / mock_decorator_service.py View on Github external
import tomodachi
from tomodachi.transport.aws_sns_sqs import aws_sns_sqs


@tomodachi.service
class MockDecoratorService(tomodachi.Service):
    name = 'mock_decorator'
    log_level = 'INFO'
    function_tested = False

    @aws_sns_sqs('test-topic')
    async def test(self, default_value: bool = True) -> None:
        self.function_tested = default_value
github kalaspuff / tomodachi / tests / services / amqp_service_with_credentials_without_protocol.py View on Github external
import asyncio
import os
import signal
import uuid
from typing import Any

import tomodachi
from tomodachi.transport.amqp import amqp, amqp_publish

data_uuid = str(uuid.uuid4())


@tomodachi.service
class AWSSNSSQSService(tomodachi.Service):
    name = 'test_amqp'
    log_level = 'INFO'
    options = {
        'amqp': {
            'login': 'guest',
            'password': 'guest'
        }
    }
    closer = asyncio.Future()  # type: Any
    test_topic_data_received = False
    test_topic_data = None
    data_uuid = data_uuid

    def check_closer(self):
        if self.test_topic_data_received:
github kalaspuff / tomodachi / tests / services / http_access_log_service.py View on Github external
import asyncio
import os
import signal
from typing import Any, Dict, Tuple  # noqa

from aiohttp import web

import tomodachi
from tomodachi.transport.http import http, http_error


@tomodachi.service
class HttpService(tomodachi.Service):
    name = 'test_http'
    options = {
        'http': {
            'port': None,
            'access_log': '/tmp/03c2ad00-d47d-4569-84a3-0958f88f6c14.log'
        }
    }
    uuid = None
    closer = asyncio.Future()  # type: Any
    slow_request = False

    def __init__(self) -> None:
        try:
            os.remove('/tmp/03c2ad00-d47d-4569-84a3-0958f88f6c14.log')
        except OSError:
github kalaspuff / tomodachi / tests / services / decorated_functions_service.py View on Github external
async def count_invocations_3(func: Any, self: Any, *args: Any, **kwargs: Any) -> None:
    self.invocation_count += 1


@tomodachi.decorator
def count_invocations_4(self: Any, *args: Any, **kwargs: Any) -> None:
    self.invocation_count += 1


@tomodachi.decorator
def count_invocations_0(self: Any, *args: Any, **kwargs: Any) -> str:
    self.invocation_count += 1
    return '0'


@tomodachi.service
class HttpService(tomodachi.Service):
    name = 'test_http'
    options = {
        'http': {
            'port': None,
            'access_log': True,
            'real_ip_from': '127.0.0.1'
        }
    }
    invocation_count = 0
    uuid = None
    closer = asyncio.Future()  # type: Any

    @http('GET', r'/count/1/?')
    @count_invocations_1
    async def count_1(self, request: web.Request) -> str:
github kalaspuff / tomodachi / examples / basic_examples / websockets / websocket_service.py View on Github external
import asyncio
import os
import pathlib
import uuid
from typing import Callable, Tuple, Union

from aiohttp import web
from aiohttp.web_fileresponse import FileResponse

import tomodachi
from tomodachi import http, http_error, http_static, websocket


@tomodachi.service
class ExampleWebsocketService(tomodachi.Service):
    name = 'example_websocket_service'
    log_level = 'DEBUG'
    uuid = os.environ.get('SERVICE_UUID')

    # Some options can be specified to define credentials, used ports, hostnames, access log, etc.
    options = {
        'http': {
            'port': 4711,
            'content_type': 'text/plain',
            'charset': 'utf-8',
            'access_log': True
        }
    }

    @http('GET', r'/(?:|index.html)')
github kalaspuff / tomodachi / examples / basic_examples / amqp_service.py View on Github external
import os
from typing import Any, Dict

import tomodachi
from tomodachi import amqp, amqp_publish
from tomodachi.discovery import DummyRegistry
from tomodachi.protocol import JsonBase


@tomodachi.service
class ExampleAmqpService(tomodachi.Service):
    name = 'example_amqp_service'
    log_level = 'INFO'
    uuid = os.environ.get('SERVICE_UUID')

    # Build own "discovery" functions, to be run on start and stop
    # See tomodachi/discovery/dummy_registry.py for example
    discovery = [DummyRegistry]

    # The message protocol class defines how a message should be processed when sent and received
    # See tomodachi/protocol/json_base.py for a basic example using JSON and transferring some metadata
    message_protocol = JsonBase

    # Some options can be specified to define credentials, used ports, hostnames, access log, etc.
    options = {
        'amqp': {
github kalaspuff / tomodachi / examples / basic_examples / http_middleware_service.py View on Github external
async def middleware_function(func: Callable, service: Any, request: web.Request, context: Dict, *args: Any, **kwargs: Any) -> Any:
    # Functionality before function is called
    service.log('middleware before')

    return_value = await func(*args, **kwargs)

    # There's also the possibility to pass in extra arguments or keywords arguments, for example:
    # return_value = await func(*args, id='overridden', **kwargs)

    # Functinoality after function is called
    service.log('middleware after')

    return return_value


@tomodachi.service
class ExampleHttpMiddlewareService(tomodachi.Service):
    name = 'example_http_middleware_service'
    log_level = 'DEBUG'
    uuid = os.environ.get('SERVICE_UUID')

    # Adds a middleware function that is run on every HTTP call.
    # Several middlewares can be chained.
    http_middleware = [middleware_function]

    # Some options can be specified to define credentials, used ports, hostnames, access log, etc.
    options = {
        'http': {
            'port': 4711,
            'content_type': 'text/plain',
            'charset': 'utf-8',
            'access_log': True
github kalaspuff / tomodachi / examples / http_service.py View on Github external
import os
import asyncio
import tomodachi
from typing import Tuple, Callable
from aiohttp import web
from tomodachi import http, http_error, http_static, websocket, HttpResponse
from tomodachi.discovery import DummyRegistry


@tomodachi.service
class ExampleHttpService(object):
    name = 'example_http_service'
    log_level = 'DEBUG'
    uuid = os.environ.get('SERVICE_UUID')

    # Build own "discovery" functions, to be run on start and stop
    # See tomodachi/discovery/dummy_registry.py for example
    discovery = [DummyRegistry]

    # Some options can be specified to define credentials, used ports, hostnames, access log, etc.
    options = {
        'http': {
            'port': 4711,
            'content_type': 'text/plain',
            'charset': 'utf-8',
            'access_log': True
github kalaspuff / tomodachi / examples / basic_examples / http_auth_service.py View on Github external
from typing import Any

from aiohttp import web

import tomodachi
from tomodachi import HttpResponse, http


@tomodachi.decorator
async def require_auth_token(instance: Any, request: web.Request) -> Any:
    post_body = await request.read() if request.body_exists else None
    if not post_body or post_body.decode() != instance.allowed_token:
        return HttpResponse(body='Invalid token', status=403)


@tomodachi.service
class ExampleHttpAuthService(tomodachi.Service):
    name = 'example_http_auth_service'
    log_level = 'DEBUG'
    allowed_token = str(uuid.uuid4())
    uuid = os.environ.get('SERVICE_UUID')

    options = {
        'http': {
            'port': 4711,
            'content_type': 'text/plain',
            'charset': 'utf-8',
            'access_log': True
        }
    }

    @http('GET', r'/get-token/?')
github kalaspuff / tomodachi / examples / basic_examples / aws_sns_sqs_middleware_service.py View on Github external
async def middleware_function(func: Callable, service: Any, message: Any, topic: str, context: Dict, *args: Any, **kwargs: Any) -> Any:
    # Functionality before function is called
    service.log('middleware before')

    return_value = await func(*args, **kwargs)

    # There's also the possibility to pass in extra arguments or keywords arguments, for example:
    # return_value = await func(*args, id='overridden', **kwargs)

    # Functinoality after function is called
    service.log('middleware after')

    return return_value


@tomodachi.service
class ExampleAWSSNSSQSService(tomodachi.Service):
    name = 'example_aws_sns_sqs_service'
    log_level = 'INFO'
    uuid = os.environ.get('SERVICE_UUID')

    # Build own "discovery" functions, to be run on start and stop
    # See tomodachi/discovery/aws_sns_registration.py for example
    discovery = [AWSSNSRegistration]

    # The message protocol class defines how a message should be processed when sent and received
    # See tomodachi/protocol/json_base.py for a basic example using JSON and transferring some metadata
    message_protocol = JsonBase

    # Adds a middleware function that is run on every incoming message.
    # Several middlewares can be chained.
    message_middleware = [middleware_function]