I am calling the code below from HTML using py-script. I am seeing that the order of events in this simple example is not what I expected. In the OUTPUT below, the displayed events are not in sequence 1,2,3,4.
Examples taken from How to make HTTP requests using PyScript, in pure Python — PyScript documentation. I also tried pyfetch and got same results.
What am I missing to make my code wait until getWords() completes before I continue to process the output?
Thanks Dan
HTML
<title>GET, POST, PUT, DELETE example</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<py-config>
[[fetch]]
files = ["request.py"]
</py-config>
PYTHON CODE
from request import request
import asyncio
import json
async def getWords():
print(“2. INSIDE GETWORDS:”)
baseurl = “http://localhost:4000/wordscape”
body = json.dumps({"sqlline": sqlline})
headers = {"Content-type": "application/json"}
myResponse = await request(f"{baseurl}/read", body=body, method="POST", headers=headers)
my_Words = await myResponse.string()
print("3. MYWORDS inside getWords:", my_Words)
sqlline = "select upper(word) as word from mydictionary where word = 'help'"
print("1. BUILD SQL:", sqlline)
my_Words = ''
asyncio.ensure_future(main())
print("4. ####WORDS RETURNED FROM getWords:",my_Words)
**OUTPUT**
1. BUILD SQL: select upper(word) as word from dictionary.dictionary_words_20230103 where word = 'help'
4. ####WORDS RETURNED FROM getWords:
2. INSIDE GETWORDS:
3. MYWORDS inside getWords: [
{
"word": "HELP"
}
]