| 1 | # |
| 2 | # Copyright (c) 2018 Joris Vink <[email protected]> |
| 3 | # |
| 4 | # Permission to use, copy, modify, and distribute this software for any |
| 5 | # purpose with or without fee is hereby granted, provided that the above |
| 6 | # copyright notice and this permission notice appear in all copies. |
| 7 | # |
| 8 | # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 9 | # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 10 | # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 11 | # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 12 | # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 13 | # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 14 | # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 15 | # |
| 16 | |
| 17 | # |
| 18 | # Asynchronous queue example. |
| 19 | # |
| 20 | |
| 21 | import kore |
| 22 | |
| 23 | # The shared queue. |
| 24 | tq = kore.queue() |
| 25 | |
| 26 | # Entry point for our independent coroutine that is created when kore starts. |
| 27 | async def queue_helper(): |
| 28 | while True: |
| 29 | # Wait for a dictionary to arrive. |
| 30 | obj = await tq.pop() |
| 31 | kore.log(kore.LOG_INFO, "coro(): received %s" % obj) |
| 32 | |
| 33 | # Create a message to send back. |
| 34 | msg = "%d = %s" % (kore.time(), obj["msg"]) |
| 35 | |
| 36 | # Send it on the received queue. |
| 37 | obj["rq"].push(msg) |
| 38 | |
| 39 | @kore.route("/queue", methods=["get"]) |
| 40 | async def async_queue(req): |
| 41 | # Create our own queue. |
| 42 | rq = kore.queue() |
| 43 | |
| 44 | # The dictionary we are going to send. |
| 45 | obj = { |
| 46 | # Receive queue object. |
| 47 | "rq": rq, |
| 48 | "msg": "hello" |
| 49 | } |
| 50 | |
| 51 | # Push it onto the tq queue now, which will wake up the other coroutine. |
| 52 | tq.push(obj) |
| 53 | |
| 54 | # Wait for a response. |
| 55 | response = await rq.pop() |
| 56 | |
| 57 | # Send the response to the client. |
| 58 | req.response(200, response.encode()) |