named-data / python-ndn

An NDN client library with AsyncIO support in Python 3
https://python-ndn.readthedocs.io/en/latest
Apache License 2.0
24 stars 17 forks source link

Make Route could be an async function #16

Closed tribela closed 3 years ago

tribela commented 4 years ago

This PR makes Route can be an async function. This is useful when route callback function must await some functions.

Normal non-async callback can be used as well.

@app.route('/some_route')
async def on_interest(name: FormalName, param: InterestParam, app_param: Optional[BinaryStr]):
    r1 = await some_awaitable_function(name)
    return r1
zjkmxy commented 4 years ago

Hello. This is left to be non-async on purpose. Incoming Interest can timeout if it is not responded in time. However, since the Interest has reached the destination already, it's not a good idea for the producer to start some time-consuming job without informing the consumer. To provide some feedback, a better practice is replying with an Application NACK (or some equivalent Data packet saying the operation cannot be finished in time). The problem is, this kind of mechanism is decided totally by application. python-ndn does not know how long your processing needs to take and what is the format of the feedback. Thus, I just leave this function to be non-async. This is to remind the developer "if you want to do something time consuming, please keep an eye on the time".

You can use asyncio.create_task to start some awaitable job.

asyncio.create_tack(some_awaitable_function(name))

You can respond to the consumer in that function.