Ask coding questions

← Back to all posts
Call Python function in HTML, JS
VulcanWM

How can I call a Python function in HTML or JavaScript?
Thanks

Answered by xfinnbar [earned 5 cycles]
View Answer
Voters
VulcanWM
Comments
hotnewtop
xfinnbar

Since Python can't run in the browser, you'll need to set up a server to run the Python function, which you can request in JavaScript.

Here is a basic example using the Flask framework:

Run that on a separate repl, then copy its' URL. Now, request it using JavaScript's fetch API:

ruiwenge2

@xfinnbar remember to allow CORS

ch1ck3n

@ruiwenge2 only when it's being requested from another domain

VulcanWM

oh okay thanks I’ll try that @xfinnbar

VulcanWM

what about in a HTML JS repl?

VulcanWM

it works thank you! @xfinnbar

ruiwenge2

also why do you need to use Python?

VulcanWM

I need Python for the account storage and stuff bc I’m more comfortable with that and JS for the main game @ruiwenge2

ruiwenge2

try using brython

VulcanWM

okay I’ll try that @ruiwenge2

Coder100

Are you looking for brython? https://brython.info/

You can use http requests to interact with flask and thus 'call' a python function.

xfinnbar

@Coder100 Brython is really slow and buggy, I don't recommend using it.

Coder100

works tho @xfinnbar

VulcanWM

okay thanks I’ll try that @Coder100