File: await.rst

package info (click to toggle)
python-klein 24.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,012 kB
  • sloc: python: 6,371; makefile: 130
file content (24 lines) | stat: -rw-r--r-- 724 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
============================
Example -- Using Async/Await
============================

The previous example which used the Twisted
:api:`twisted.internet.defer.Deferred <Deferred>` class
can be written to use the new ``async`` and ``await``
keywords that are available in Python 3.5+.

Here is the same Google proxy, using `treq <https://github.com/twisted/treq>`_ and ``async`` and ``await``.

.. code-block:: python

    import treq
    from klein import Klein
    app = Klein()

    @app.route('/', branch=True)
    async def google(request):
        response = await treq.get(b'https://www.google.com' + request.uri)
        content = await treq.content(response)
        return content

    app.run("localhost", 8080)