Example #1
0
File: app.py Project: yws/Kyoukai
    def run(self, ip: str = "127.0.0.1", port: int = 4444, *, component=None):
        """
        Runs the Kyoukai server from within your code.

        This is not normally invoked - instead Asphalt should invoke the Kyoukai component.
        However, this is here for convenience.
        """
        if not component:
            from kyoukai.asphalt import KyoukaiComponent
            component = KyoukaiComponent(self, ip, port)

        run_application(component)
Example #2
0
"""This is the client code for the Asphalt echo server tutorial."""
import sys
from asyncio import get_event_loop, open_connection

from asphalt.core import Component, run_application


class ClientComponent(Component):
    def __init__(self, message: str):
        self.message = message

    async def start(self, ctx):
        reader, writer = await open_connection('localhost', 64100)
        writer.write(self.message.encode() + b'\n')
        response = await reader.readline()
        writer.close()
        print('Server responded:', response.decode().rstrip())
        get_event_loop().stop()


if __name__ == '__main__':
    msg = sys.argv[1]
    component = ClientComponent(msg)
    run_application(component)
Example #3
0
from asphalt.core import CLIApplicationComponent, Context, run_application
from asphalt.serialization.serializers.cbor import CBORSerializer

logger = logging.getLogger(__name__)


class FileGetterComponent(CLIApplicationComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp', serializer=CBORSerializer())
        await super().start(ctx)

    async def run(self, ctx: Context):
        def on_progress(data: bytes):
            # This gets called for every chunk the server sends (ctx.progress() on the other side)
            outfile.write(data)
            print('\r{} bytes written'.format(outfile.tell()), end='')

        remote_path = sys.argv[1]
        local_path = Path(mkdtemp()) / Path(remote_path).name
        with local_path.open('wb') as outfile:
            await ctx.wamp.call('send_file', remote_path, on_progress=on_progress)

        print('\nFile saved as %s' % local_path)


if len(sys.argv) < 2:
    print('Usage: {} <file path>'.format(sys.argv[0]), file=sys.stderr)
    sys.exit(1)

run_application(FileGetterComponent(), logging=logging.INFO)
Example #4
0
"""This is the client code for the Asphalt echo server tutorial."""
import sys
from asyncio import open_connection

from asphalt.core import CLIApplicationComponent, run_application


class ClientComponent(CLIApplicationComponent):
    def __init__(self, message: str):
        super().__init__()
        self.message = message

    async def run(self, ctx):
        reader, writer = await open_connection('localhost', 64100)
        writer.write(self.message.encode() + b'\n')
        response = await reader.readline()
        writer.close()
        print('Server responded:', response.decode().rstrip())

if __name__ == '__main__':
    component = ClientComponent(sys.argv[1])
    run_application(component)
    def __init__(self, attachment):
        super().__init__()
        self.attachment = attachment

    async def start(self, ctx: Context):
        self.add_component(
            "mailer", backend="smtp", host="smtp.example.org", ssl=True, username="******", password="******"
        )
        await super().start(ctx)

    async def run(self, ctx: Context):
        message = ctx.mailer.create_message(
            subject="Test email with attachment",
            sender="Sender <*****@*****.**>",
            to="Recipient <*****@*****.**>",
            plain_body="Take a look at this file!",
        )
        await ctx.mailer.add_file_attachment(message, self.attachment)
        await ctx.mailer.deliver(message)


if len(sys.argv) < 2:
    print("Specify the path to the attachment as the argument to this script!", file=sys.stderr)
    sys.exit(1)

if not os.path.isfile(sys.argv[1]):
    print("The attachment ({}) does not exist or is not a regular file", file=sys.stderr)
    sys.exit(2)

run_application(ApplicationComponent(sys.argv[1]), logging=logging.DEBUG)
"""This example demonstrates how to publish messages with WAMP."""

import logging
import sys

from asphalt.core import CLIApplicationComponent, Context, run_application

logger = logging.getLogger(__name__)


class PublisherComponent(CLIApplicationComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp')
        await super().start(ctx)

    async def run(self, ctx: Context):
        topic, message = sys.argv[1:3]
        await ctx.wamp.publish(topic, message)


if len(sys.argv) < 3:
    print('Usage: {} <topic> <message>'.format(sys.argv[0]), file=sys.stderr)
    sys.exit(1)

run_application(PublisherComponent(), logging=logging.INFO)
Example #7
0
"""This example demonstrates how to find out the caller's authentication ID (username)."""

import logging

from asphalt.core import ContainerComponent, Context, run_application
from asphalt.wamp.context import CallContext


def hello(ctx: CallContext):
    return 'Hello, {}!'.format(ctx.caller_auth_id)


class RPCServerComponent(ContainerComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp',
                           url='ws://localhost:8080',
                           auth_method='wampcra',
                           auth_id='testserver',
                           auth_secret='server123')
        await super().start(ctx)

        await ctx.wamp.register_procedure(hello, 'hello')


run_application(RPCServerComponent(), logging=logging.INFO)
Example #8
0
        # Remove the db file if it exists
        db_path = self.csv_path.with_name('people.db')
        if db_path.exists():
            db_path.unlink()

        self.add_component('sqlalchemy', url='sqlite:///{}'.format(db_path))
        await super().start(ctx)

        # Create the table in a subcontext – never use connections or sessions from a long lived
        # context!
        async with Context(ctx):
            Base.metadata.create_all(ctx.sql.bind)

    async def run(self, ctx: Context):
        async with ctx.threadpool():
            num_rows = 0
            with self.csv_path.open() as csvfile:
                reader = csv.reader(csvfile, delimiter='|')
                for name, city, phone, email in reader:
                    num_rows += 1
                    ctx.sql.add(
                        Person(name=name, city=city, phone=phone, email=email))

            # Emit pending INSERTs (though this would happen when the context ends anyway)
            ctx.sql.flush()

        logger.info('Imported %d rows of data', num_rows)


run_application(CSVImporterComponent(), logging=logging.DEBUG)
Example #9
0
"""
This example demonstrates how to find out the caller's authentication ID (username).
It should be noted that for this to work with Crossbar at least, caller disclosure must be enabled
in the authentication configuration.
"""

import logging

from asphalt.core import ContainerComponent, Context, run_application
from asphalt.wamp.context import CallContext


def hello(ctx: CallContext):
    return 'Hello, {}!'.format(ctx.caller_auth_id)


class RPCServerComponent(ContainerComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp', auth_method='wampcra',
                           auth_id='testserver', auth_secret='server123')
        await super().start(ctx)

        await ctx.wamp.register(hello, 'hello')


run_application(RPCServerComponent(), logging=logging.INFO)
class ApplicationrComponent(ContainerComponent):
    async def start(self, ctx: Context):
        csv_path = Path(__file__).with_name('people.csv')
        db_path = csv_path.with_name('people.db')

        # Remove any existing db file
        if db_path.exists():
            db_path.unlink()

        self.add_component('sqlalchemy', url='sqlite:///{}'.format(db_path),
                           metadata=Base.metadata)
        await super().start(ctx)

        # Create the table
        Base.metadata.create_all()

        async with threadpool():
            num_rows = 0
            with csv_path.open() as csvfile:
                reader = csv.reader(csvfile, delimiter='|')

                # Import each row into the session as a new Person instance
                for name, city, phone, email in reader:
                    num_rows += 1
                    ctx.dbsession.add(Person(name=name, city=city, phone=phone, email=email))

        logger.info('Imported %d rows of data', num_rows)
        asyncio.get_event_loop().stop()

run_application(ApplicationrComponent(), logging=logging.DEBUG)
def main(host, username, password, sender, to, subject, attachment):
    component = ApplicationComponent(host, username, password, sender, to,
                                     subject, attachment)
    run_application(component, logging=logging.INFO)
Example #12
0
logger = logging.getLogger(__name__)


class FileGetterComponent(ContainerComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp', url='ws://localhost:8080')
        await super().start(ctx)

        def on_progress(data: bytes):
            # This gets called for every chunk the server sends (ctx.progress() on the other side)
            outfile.write(data)
            print('\r{} bytes written'.format(outfile.tell()), end='')

        remote_path = sys.argv[1]
        local_path = Path(mkdtemp()) / Path(remote_path).name
        with local_path.open('wb') as outfile:
            await ctx.wamp.call('send_file',
                                remote_path,
                                on_progress=on_progress)

        print('\nFile saved as %s' % local_path)
        asyncio.get_event_loop().stop()


if len(sys.argv) < 2:
    print('Usage: {} <file path>'.format(sys.argv[0]), file=sys.stderr)
    sys.exit(1)

run_application(FileGetterComponent(), logging=logging.INFO)
Example #13
0
"""
This example demonstrates how to publish messages with WAMP.

First start subscriber.py and take note of which port it's running on.
"""

import asyncio
import logging
import sys

from asphalt.core import ContainerComponent, Context, run_application

logger = logging.getLogger(__name__)


class PublisherComponent(ContainerComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp', url='ws://localhost:8080')
        await super().start(ctx)

        topic, message = sys.argv[1:3]
        await ctx.wamp.publish(topic, message)
        asyncio.get_event_loop().stop()


if len(sys.argv) < 3:
    print('Usage: {} <topic> <message>'.format(sys.argv[0]), file=sys.stderr)
    sys.exit(1)

run_application(PublisherComponent(), logging=logging.INFO)
"""A simple example that serializes a dictionary and prints out the result."""
import asyncio

from asphalt.core import ContainerComponent, Context, run_application


class ApplicationComponent(ContainerComponent):
    async def start(self, ctx: Context):
        self.add_component('serialization', backend='json')
        await super().start(ctx)

        payload = ctx.json.serialize(
            {'a': 1, 'b': 5.03, 'c': [1, 2, 3], 'd': {'x': 'nested'}})
        print('JSON serialized dict:', payload.decode())
        asyncio.get_event_loop().stop()

run_application(ApplicationComponent())
Example #15
0
and use PackageLoader with the ``package_name`` option so they can be accessed
regardless of where the application has been installed.
"""

from pathlib import Path
from uuid import uuid1

from asphalt.core import CLIApplicationComponent, Context, run_application
from jinja2 import FileSystemLoader


class ApplicationComponent(CLIApplicationComponent):
    async def start(self, ctx: Context):
        this_directory = str(Path(__file__).parent)
        self.add_component(
            "templating",
            backend="jinja2",
            options={
                "loader_class": FileSystemLoader,
                "searchpath": this_directory,
            },
        )
        await super().start(ctx)

    async def run(self, ctx: Context):
        rendered = ctx.jinja2.render("demo.jinja2", uuid=uuid1())
        print(rendered)


run_application(ApplicationComponent())
"""This example demonstrates how to subscribe to topics with WAMP."""

import logging
import sys

from asphalt.core import ContainerComponent, Context, run_application
from asphalt.wamp.context import EventContext

logger = logging.getLogger(__name__)


def subscriber(ctx: EventContext, message: str):
    logger.info('Received message from %s: %s', ctx.topic, message)


class SubscriberComponent(ContainerComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp')
        await super().start(ctx)

        topic = sys.argv[1]
        await ctx.wamp.subscribe(subscriber, topic)
        logger.info('Subscribed to topic: %s', topic)


if len(sys.argv) < 2:
    print('Usage: {} <topic>'.format(sys.argv[0]), file=sys.stderr)
    sys.exit(1)

run_application(SubscriberComponent(), logging=logging.INFO)
def stream(url, interval):
    component = FeedReaderApp(url, interval)
    run_application(component)
Example #18
0
from asphalt.core import ContainerComponent, Context, run_application
from asphalt.wamp.context import CallContext, EventContext
from asphalt.wamp.registry import WAMPRegistry

topics = WAMPRegistry('topics')
procedures = WAMPRegistry('test')


@procedures.procedure
async def reverse(ctx: CallContext, message: str):
    return message[::-1]


@topics.subscriber('subtopic')
async def subtopic(ctx: EventContext, message):
    print('message received from topic.subtopic: %s' % message)


class RPCServerComponent(ContainerComponent):
    async def start(self, ctx: Context):
        registry = WAMPRegistry()
        registry.add_from(topics)
        registry.add_from(procedures)
        self.add_component('wamp', registry=registry)
        await super().start(ctx)
        await ctx.wamp.connect()


run_application(RPCServerComponent(), logging=logging.DEBUG)
Example #19
0
"""
This example WAMP client first calls the ``test.reverse`` remote method with string given as the
command line. It then publishes the return value on the ``topics.subtopic`` topic.
"""

import logging
import sys

from asphalt.core import CLIApplicationComponent, Context, run_application


class RPCClientComponent(CLIApplicationComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp')
        await super().start(ctx)

    async def run(self, ctx: Context):
        message = sys.argv[1]
        result = await ctx.wamp.call('test.reverse', message)
        await ctx.wamp.publish('topics.subtopic', result)


if len(sys.argv) < 2:
    print('Usage: {} <text>'.format(sys.argv[0]), file=sys.stderr)
    sys.exit(1)

run_application(RPCClientComponent(), logging=logging.INFO)
Example #20
0
"""
This example WAMP client first calls the ``test.reverse`` remote method with string given as the
command line. It then publishes the return value on the ``topic.subtopic`` topic.
"""

import asyncio
import logging
import sys

from asphalt.core import ContainerComponent, Context, run_application


class RPCClientComponent(ContainerComponent):
    async def start(self, ctx: Context):
        self.add_component('wamp', url='ws://localhost:8080')
        await super().start(ctx)

        message = sys.argv[1]
        result = await ctx.wamp.call('test.reverse', message)
        await ctx.wamp.publish('topic.subtopic', result)
        asyncio.get_event_loop().stop()


if len(sys.argv) < 2:
    print('Usage: {} <text>'.format(sys.argv[0]), file=sys.stderr)
    sys.exit(1)

run_application(RPCClientComponent(), logging=logging.INFO)
Example #21
0
def stream(interval):
    component = CustomFeedReaderApp(interval)
    run_application(component)