| 1 | # |
| 2 | # Copyright (c) 2017-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 | # Asynchronous postgresql queries with Python. |
| 18 | |
| 19 | import json |
| 20 | import kore |
| 21 | |
| 22 | class KoreApp: |
| 23 | def configure(self, args): |
| 24 | # Register the path to our database when Kore starts. |
| 25 | kore.dbsetup("db", "host=/tmp dbname=test") |
| 26 | |
| 27 | # A handler that returns 200 OK with hello as body. |
| 28 | def hello(self, req): |
| 29 | req.response(200, b'hello\n') |
| 30 | |
| 31 | # |
| 32 | # The query handler that fires of the query and returns a coroutine. |
| 33 | # |
| 34 | # Kore will resume this handler when the query returns a result or |
| 35 | # is successful. |
| 36 | # |
| 37 | # The kore.pgsql() method can throw exceptions, most notably a |
| 38 | # GeneratorExit in case the client connection went away before |
| 39 | # the query was able to be completed. |
| 40 | # |
| 41 | # In this example we're not doing any exception handling. |
| 42 | # |
| 43 | async def query(self, req): |
| 44 | result = await kore.dbquery("db", "SELECT * FROM coders") |
| 45 | req.response(200, json.dumps(result).encode("utf-8")) |
| 46 | |
| 47 | # |
| 48 | # A slow query that returns after 10 seconds. |
| 49 | # |
| 50 | async def slow(self, req): |
| 51 | result = await kore.dbquery("db", "SELECT * FROM pg_sleep(10)") |
| 52 | req.response(200, json.dumps(result).encode("utf-8")) |
| 53 | |
| 54 | # Set the application Kore will run to our class. |
| 55 | koreapp = KoreApp() |