I have a basic flask application, where one of the routes calls a new thread and returns like this:
@app.route("/beginDelivery", methods=["POST"])
def begin_delivery():
if request.get_json(force=True):
js = request.json
else:
return jsonify(status=wrong_json())
pid = js['pid']
Thread(target=asynchronously_deliver, args=[pid]).start()
return jsonify(status=0)
Now, in my asynchronously_deliver function, there is a loop that calls send_sms function. send_sms does not have any loop and it ends like this:
#....
#....
print("sending sms...")
rb = urllib.request.urlopen("someurl").read()
rsp = str(rb.decode('utf-8'))
if rsp[0] == '0' and rsp[1] == '0' and rsp[2] == '0' and rsp[3] == '0':
provider_id = rsp[7:]
print("provider: success")
else:
provider_id = '0'
print("provider: error")
return provider_id
Now, the issue is, that when I examine the console, sometimes, instead of
sending sms...
127.0.0.1 - - [19/May/2016 10:16:54] "GET /someurl HTTP/1.1" 200 -
provider: success
I get
sending sms...
provider: success
127.0.0.1 - - [19/May/2016 10:16:56] "GET /someurl HTTP/1.1" 200 -
Meaning that for some reason, in send_sms both prints where executed before urllib.request.urlopen("someurl").read().
What could be the reason?
EDIT:
I added sleep(10) to my /someurl route and there was a 10 second delay between sending sms... and provider: success. Although, consider this:
127.0.0.1 - - [19/May/2016 11:32:06] "GET /someurl
wasn't printed until 10 seconds elapsed, right before provider:success, therefore, flask doesn't send the message to console until the request is completed and response is returned. Also, that means (I think) that rb = urllib.request.urlopen("someurl").read() is not called asynchronously. Am I wrong?