Exemplo n.º 1
0
async def websocket_handler(request):
    print("WebSocket opened")

    stream = AsyncStream()

    xs = (
        stream
        | op.map(lambda x: x["term"])
        | op.filter(lambda text: len(text) > 2)
        | op.debounce(0.5)
        | op.distinct_until_changed()
        | op.flat_map(search_wikipedia)
    )

    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async def asend(value) -> None:
        ws.send_str(value)

    async def athrow(ex) -> None:
        print(ex)

    await subscribe(xs, AsyncAnonymousObserver(asend, athrow))

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            obj = json.loads(msg.data)
            await stream.asend(obj)

        elif msg.type == aiohttp.WSMsgType.ERROR:
            print("ws connection closed with exception %s" % ws.exception())

    print("websocket connection closed")
    return ws
Exemplo n.º 2
0
async def test_withlatestfrom_done():
    xs = AsyncStream()
    ys = AsyncStream()
    result = []

    async def asend(value):
        log.debug("test_withlatestfrom_done:asend(%s)", value)
        nonlocal result
        asyncio.sleep(0.1)
        result.append(value)

    zs = with_latest_from(lambda x, y: x + y, ys, xs)

    sub = await subscribe(zs, AnonymousAsyncObserver(asend))
    await xs.asend(1)
    await ys.asend(2)
    await xs.asend(3)
    await xs.aclose()
    await sub

    assert result == [5]
Exemplo n.º 3
0
async def test_debounce_filter():
    xs = AsyncStream()
    result = []

    async def asend(value):
        log.debug("test_debounce_filter:asend(%s)", value)
        nonlocal result
        result.append(value)

    ys = debounce(0.5, xs)
    sub = await subscribe(ys, AnonymousAsyncObserver(asend))
    await xs.asend(1)
    await asyncio.sleep(0.3)
    await xs.asend(2)
    await xs.aclose()
    await asyncio.sleep(0.6)
    await sub

    assert result == [2]
Exemplo n.º 4
0
async def test_flap_map_done():
    xs = AsyncStream()
    result = []

    async def asend(value):
        nonlocal result
        result.append(value)

    async def mapper(value):
        return from_iterable([value])

    ys = flat_map(mapper, xs)
    await subscribe(ys, AnonymousAsyncObserver(asend))
    await xs.asend(10)
    await xs.asend(20)

    await asyncio.sleep(0.6)

    assert result == [10, 20]
Exemplo n.º 5
0
async def test_debounce():
    xs = AsyncStream()
    result = []

    async def asend(value):
        log.debug("test_debounce:asend(%s)", value)
        nonlocal result
        result.append(value)

    ys = debounce(0.5, xs)

    obv = AsyncAnonymousObserver(asend)
    sub = await subscribe(ys, obv)
    await xs.asend(1)
    await asyncio.sleep(0.6)
    await xs.asend(2)
    await xs.aclose()
    await asyncio.sleep(0.6)
    await obv

    assert result == [1, 2]
Exemplo n.º 6
0
async def test_map_subscription_cancel():
    xs = AsyncStream()
    result = []
    sub = None

    def mapper(value):
        return value * 10

    ys = xs | _.map(mapper)

    async def asend(value):
        result.append(value)
        await sub.adispose()
        await asyncio.sleep(0)

    async with subscribe(ys, AsyncAnonymousObserver(asend)) as sub:

        await xs.asend(10)
        await asyncio.sleep(0)
        await xs.asend(20)

    assert result == [100]
Exemplo n.º 7
0
async def test_flap_map_done():
    xs = AsyncStream()
    result = []

    async def asend(value):
        nonlocal result
        result.append(value)

    async def mapper(value):
        return from_iterable([value])

    ys = flat_map(mapper, xs)

    obv = AsyncAnonymousObserver()
    await subscribe(ys, obv)
    await xs.asend(10)
    await xs.asend(20)
    await xs.aclose()

    await obv

    assert obv.values == [(0, 10), (0, 20), (0, )]
Exemplo n.º 8
0
async def main(loop) -> None:
    root = Tk()
    root.title("aioreactive")

    mousemoves = AsyncStream()

    frame = Frame(root, width=800, height=600)

    async def move(event) -> None:
        await mousemoves.asend(event)

    def call_move(event):
        asyncio.ensure_future(move(event))

    frame.bind("<Motion>", call_move)

    text = "TIME FLIES LIKE AN ARROW"
    labels = [Label(frame, text=c) for c in text]

    async def handle_label(i, label) -> None:
        label.config(dict(borderwidth=0, padx=0, pady=0))

        async def asend(ev) -> None:
            label.place(x=ev.x + i * 12 + 15, y=ev.y)

        obv = AsyncAnonymousObserver(asend)

        await (mousemoves | delay(i / 10.0) > obv)

    for i, label in enumerate(labels):
        await handle_label(i, label)

    frame.pack()

    # A simple combined event loop
    while True:
        root.update()
        await asyncio.sleep(0.005)
Exemplo n.º 9
0
async def websocket_handler(request):
    print("WebSocket opened")

    stream = AsyncStream()

    # Line break before binary operator is more readable. Disable W503
    xs = (
        stream
        | op.map(lambda x: x["term"])
        | op.filter(lambda text: len(text) > 2)
        | op.debounce(0.75)
        | op.distinct_until_changed()
        | op.flat_map(search_wikipedia)
        #| op.switch_latest()
    )

    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async def asend(value):
        ws.send_str(value)

    async def athrow(ex):
        print(ex)

    await subscribe(xs, AnonymousAsyncObserver(asend, athrow))

    async for msg in ws:
        if msg.type == aiohttp.WSMsgType.TEXT:
            obj = json.loads(msg.data)
            await stream.asend(obj)

        elif msg.type == aiohttp.WSMsgType.ERROR:
            print('ws connection closed with exception %s' % ws.exception())

    print('websocket connection closed')
    return ws
Exemplo n.º 10
0
async def test_map_subscription_cancel():
    xs = AsyncStream()
    result = []
    sub = None

    def mapper(value):
        return value * 10

    print("-----------------------")
    print([xs, op.map])
    ys = xs | op.map(mapper)

    async def asend(value):
        result.append(value)
        sub.dispose()
        await asyncio.sleep(0)

    async with subscribe(ys, AnonymousAsyncObserver(asend)) as sub:

        await xs.asend(10)
        await asyncio.sleep(0)
        await xs.asend(20)

    assert result == [100]
Exemplo n.º 11
0
import collections

import peony
from aioreactive.core import AsyncStream

from feed import settings

client = peony.PeonyClient(**settings.TWITTER)

latest_tweets = collections.deque(maxlen=settings.LATEST_TWEETS_COUNT)

new_tweets_stream = AsyncStream()


async def track_tweets():
    async with client.stream.statuses.filter.post(
            track=settings.TWITTER_TRACK) as stream:
        async for tweet in stream:
            if 'error' not in tweet and 'text' in tweet:
                latest_tweets.appendleft(tweet)
                await new_tweets_stream.asend(tweet)


async def fetch_tweets():
    response = await client.api.search.tweets.get(q=settings.TWITTER_TRACK)
    latest_tweets.extend(response['statuses'])


async def initialize(app):
    await fetch_tweets()
    app.loop.create_task(track_tweets())