有没有一种简单的方法可以让 html 按钮执行 python 函数

时间:2021-04-15 06:53:18

标签: python html button

我有一个 python 函数,它创建一个带有输出/结果的 .txt 文件并将其保存在我的项目目录中。现在我有一个 html js 文件,我从 .txt 文件中获取数据,然后使用它并显示数据。

现在我的问题是,我想要一个按钮来执行 python 脚本并根据变量创建新数据。

有没有简单的方法来做到这一点。

我对 Web 应用程序编程还很陌生。

2 个答案:

答案 0 :(得分:1)

你可以使用像flask这样的框架。使用flask,您只需将您的函数粘贴到一个根目录上,该根目录将在您继续使用该根目录时执行。 只需将表单操作设置为您的根,然后让您的方法像它一样:

<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>

然后在你的python文件中:

def your_function():
 ...

答案 1 :(得分:0)

浏览器没有读取本地文件系统的权限。所以你必须先提供 .txt 文件。

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>

foo.txtfoo.html的同一目录下启动HTTP Server

python3 -mhttp.server 8888

然后打开 http://localhost:8888/foo.html 查看结果。