A simple example project for using websockets to call python functions from javascript.
- Clone the repository and open terminal in the folder
- Run
python -m pip install -r requirements.txt
- Run
python __main__.py
- Open http://127.0.0.1:8000/ in your browser
- Follow the instructions on the website
All functions that you can call from javascript are defined in api.py
.
If the function defined in python looks like this
def add(a, b):
return a + b
Then it can be called in javascript like this
let resultPromise = api.add(4,5);
The result is a promise, so you should either
call the function from inside an async
function with await
, like this:
async function myFunction() {
const result = await api.add(4,5);
console.log(`The result was ${result}`)
}
myFunction()
Or by calling .then
on the promise with a callback.
api.add(4,5).then(result=>console.log(`The result was ${result}`))