Reputation: 1341
I have a basic flask app to serve twilio calls.
When a call is generated via twilio it goes to my /test
http api.
In this api I'm generating a twiml conversation where the first thing that happens is a verb just saying "hello world". Then, concurrently I start a stream in the background. I'm using flask_sock
for handling websocket connections in my flask app.
Here is my flask app route function that gets executed when the twilio call starts
@app.route('/test', methods=['POST'])
def test():
response = VoiceResponse()
connect = Connect()
connect.stream(url=f'wss://{request.host}/stream')
response.say("hello world")
response.append(connect)
response.pause(length=30)
return str(response), 200, {'Content-Type': 'text/xml'}
Everything works when my stream is not async.
@sock.route('/stream')
def stream(ws):
do_something()
When I try to make my stream function async, like this:
@sock.route('/stream')
async def stream(ws):
await do_something()
I get RuntimeWarning: coroutine 'stream' was never awaited
And my socket gets automatically terminated (ConnectionError
)
How can I make this work with async?
For extra context: I'm running my flask app like this and then just running flask run
app = Flask(__name__)
sock = Sock(app)
... functions described above
if __name__ == '__main__':
app.run(debug=True)
I cannot await the stream function because I'm not calling it, it's just a websocket entrypoint for twilio to initiate..
Upvotes: 0
Views: 395
Reputation: 623
Hopefully this documentation helps, TwiML Voice: < Stream >.
Per the documentation,
The < Start > verb starts the audio < Stream > asynchronously and immediately continues with the next TwiML instruction. If there is no instruction, the call will be disconnected. In order to avoid this, provide a TwiML instruction to continue the call.
If you'd prefer a synchronous bi-directional stream, you should use the < Connect > verb.
So instead of connect
, try start
!
Upvotes: 0