| 1 | # |
| 2 | # Copyright (c) 2019 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 HTTP client example. |
| 19 | # |
| 20 | |
| 21 | import kore |
| 22 | |
| 23 | # Handler called for /httpclient |
| 24 | @kore.route("/httpclient", methods=["get"]) |
| 25 | async def httpclient(req): |
| 26 | # Create an httpclient. |
| 27 | client = kore.httpclient("https://kore.io") |
| 28 | |
| 29 | # Do a simple GET request. |
| 30 | print("firing off request") |
| 31 | status, body = await client.get() |
| 32 | print("status: %d, body: '%s'" % (status, body)) |
| 33 | |
| 34 | # Reuse and perform another GET request, returning headers too this time. |
| 35 | status, headers, body = await client.get(return_headers=True) |
| 36 | print("status: %d, headers: '%s'" % (status, headers)) |
| 37 | |
| 38 | # What happens if we post something? |
| 39 | status, body = await client.post(body=b"hello world") |
| 40 | print("status: %d, body: '%s'" % (status, body)) |
| 41 | |
| 42 | # Add some custom headers to our requests. |
| 43 | status, body = await client.get( |
| 44 | headers={ |
| 45 | "x-my-header": "async-http" |
| 46 | } |
| 47 | ) |
| 48 | |
| 49 | req.response(200, b'async done') |