Is there an easy way to let a html button execute a python function

Viewed 24

I have a python function that creates a .txt file with an output / results and saves it in my project directory. Now i have a html js files where i take that data from the .txt file and i use it and display the data.

Now my problem is, i want to have a button that executes the python script and creates fresh data depending on a variable.

Is there an easy way to do it.

I am quite new to programming web applications.

2 Answers

you can use frameworks like flask. with flask you just paste your function with a root that will be executed when you go on that root. just set Form action to your root and then make your method there like it:

<form method="POST" action={{ url_for('your_function') }}>
<div style="text-align: center;">
<H1>Admin panel login </H1> <br>
Username <input type = "text" name= "username" /> <br>
Password <input type = "password" name = "password" /> <br>
<input type = "submit">
</div>
</form>

then in your python file :

def your_function():
 ...

Browser has no permission to read local file system. So you must serve the .txt file first.

foo.txt

Foo
Bar
Baz

foo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
</body>
<script>
    fetch("foo.txt").then(x => x.text()).then(text => document.getElementsByTagName("body")[0].innerText = text)
</script>
</html>

Start HTTP Server in same directory of foo.txt and foo.html

python3 -mhttp.server 8888

Then open http://localhost:8888/foo.html to see the result.

Related