【问题标题】:Running a python script with website input使用网站输入运行 python 脚本
【发布时间】:2017-08-26 21:26:14
【问题描述】:

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

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

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

run python script with html button

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

【问题讨论】:

    标签: javascript jquery python html ajax


    【解决方案1】:

    在网页和 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 方面来看这会是怎样的吗?假设您在上面编写的代码称为“helloWorld.py”,并且在命令行中它接受参数“hello”,那么您如何传递脚本“hello”并在 JS 方面接收脚本的响应?
    • WSGI 服务器只是在监听 http 请求,它的返回值——不管它们是什么——将被发送以响应请求。这个问题包括一堆在 JS 中执行此操作的不同方法的示例:stackoverflow.com/questions/247483/…
    • 感谢您的帮助,但我仍然没有运气。我已经修改了 python 脚本来简单地创建一个 html 页面。所以从字面上看,我所需要的就是弄清楚这个的javascript方面。我只需要向脚本传递一个字符串并运行它。 (整个脚本,不仅仅是其中的一个函数。即:$ python3 myscript.py inputString
    • 那么您正在创建一个服务器,它将返回脚本数据作为结果(它可以是格式化的 html 或只是文本)。我上面链接的答案显示了如何发送请求,如果您必须将数据打包到请求的 URL 中,例如 fetch("http://you/url/here?param=somevalue") 您将编写服务器来解析查询字符串并在结果中处理它.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多