简体   繁体   中英

Issue with asynchronous (non blocking) methods with Sanic

So I'm trying to use Sanic to to some asynchronous web requests as I have some special ones that take a few seconds to get back, but want to do other requests in the mean time from the client. Here is an example method that seems to still be blocking other calls from the client while its waiting for the lib.getAlarmState() to come back. (lib.getAlartmState() is a call to a C library using pythons ctypes that takes about 3 seconds to return and returns an Int type.)

According to what I'm seeing in documentation for sanic, simply defining the method as async should do what I'm looking to do? I've tried adding an await in front of lib.getAlarmState() but I'm not sure I'm using that quite right.

@app.route('/processjson')
async def processjson(request):

    vals = lib.getAlarmState()

    return response.json({"alarm:" : vals})

I expect that while the shown method is off doing its thing, I should be able to call other methods from the client and get responses.

That is correct. Sanic will not be able to convert blocking calls to asynchronous. Perhaps, what you can try instead is to run that in a seperate task.

async def get_alarm_state_wrapper():
    return lib.getAlarmState()

@app.route('/processjson')
async def processjson(request):

    vals = await asyncio.gather(get_alarm_state_wrapper())

    return response.json({"alarm:" : vals})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM