gpt4 book ai didi

javascript - 使用网站输入运行 python 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:47 25 4
gpt4 key购买 nike

我有一些 webdev 经验,并且刚刚开始学习 python。我创建了一个 python 脚本,它接受一个参数,然后运行一个程序,并将打印语句打印到控制台中。我很好奇是否可以将此程序放在网页后面。

即带有下拉菜单的网页,选择选项并单击“执行”按钮。然后,Python 脚本将使用您选择的选项运行,您的报告将显示在页面上。

我看过一些类似的帖子:Execute a python script on button click

run python script with html button

但他们似乎提供了非常不同的解决方案,而且人们似乎认为 PhP 的想法是不安全的。我也在寻找更明确的东西。我可以更改 python 脚本以返回 ajson 或其他内容,而不仅仅是打印语句。

最佳答案

网页和 python 程序之间进行通信的一种非常常见的方法是将 python 作为 WSGI server 运行。 。实际上,Python 程序是一个单独的服务器,它使用 GET 和 POST 与网页进行通信。

这种方法的一个好处是它将 Python 应用程序与网页本身分离。您可以在开发时通过将 http 请求直接发送到测试服务器来测试它。

Python 包含 built-in WSGI implementation ,因此创建 WSGI 服务器非常简单。这是一个非常简单的示例:

from wsgiref.simple_server import make_server

# this will return a text response
def hello_world_app(environ, start_response):
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/plain')] # HTTP Headers
start_response(status, headers)
return ["Hello World"]

# first argument passed to the function
# is a dictionary containing CGI-style environment variables
# second argument is a function to call
# make a server and turn it on port 8000
httpd = make_server('', 8000, hello_world_app)
httpd.serve_forever()

关于javascript - 使用网站输入运行 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43160464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com