Skip to content
Sign upLog in
← Back to Community
Call Python function in HTML, JS
Profile icon
VulcanWM

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

Answered by xfinnbar [earned 5 cycles]
View Answer
Voters
Profile icon
VulcanWM
Comments
hotnewtop
Profile icon
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:

from flask import Flask app = Flask(__name__) @app.route("/doubletwo") def doubletwo(): return 2 * 2 app.run("0.0.0.0")

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

async function main() { let r = await fetch("https://your-url.repl.co/doubletwo") // replace this with your url if (r.ok) { let text = await r.text() alert("Return value from function: " + text) } else { alert("There was an error") } } main()
Profile icon
ruiwenge2

@xfinnbar
remember to allow CORS

Profile icon
ch1ck3n

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

Profile icon
VulcanWM

oh okay thanks I’ll try that

@xfinnbar

Profile icon
VulcanWM

what about in a HTML JS repl?

Profile icon
VulcanWM

it works thank you!

@xfinnbar

Profile icon
Bluestonex64

@xfinnbar
Im only getting the code for the python file, I'm fetching, and its not returning the value of the function, is there something I'm missing? Cause I literally copy pasted the code lmao

Profile icon
ruiwenge2

also why do you need to use Python?

Profile icon
VulcanWM

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

@ruiwenge2

Profile icon
ruiwenge2

try using brython

Profile icon
VulcanWM

okay I’ll try that

@ruiwenge2

Profile icon
Coder100

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

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

Profile icon
xfinnbar

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

Profile icon
Coder100

works tho

@xfinnbar

Profile icon
VulcanWM

okay thanks I’ll try that

@Coder100