javascript 从javascript执行python脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32525613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:24:50  来源:igfitidea点击:

execute python script from javascript

javascriptpythonajax

提问by llams48

I am a newbie to python. I am working on a web app and trying to call a python script from a js script. I am using ajax to call the .py script as follows but I just keep getting the code returned in the response. For simplicity, I have reduced the computation in the python script - even the variable x is not being returned to the js file.

我是python的新手。我正在开发一个 Web 应用程序并尝试从 js 脚本调用 python 脚本。我正在使用 ajax 调用 .py 脚本,如下所示,但我只是不断获取响应中返回的代码。为简单起见,我减少了 python 脚本中的计算——甚至变量 x 也没有返回到 js 文件。

in js function

在js函数中

  return $.ajax({
    type: 'GET',
    url: 'test.py',

    success: function(response) {
      console.log(response);
    },
    error: function(response) {
      return console.error(response);
    }
  });

test.py

测试文件

#!/usr/bin/python

print("Hello World")

x = 2
return x

The request succeeds because it moves inside success. response is the python code instead of 2. Thanks for your help!

请求成功,因为它在成功中移动。响应是python代码而不是2。感谢您的帮助!

回答by Ivan Velichko

You have to use a so called application server to serve HTTP requests in Python. Look at this oneor try to use some lightweight web frameworks like Flask.

您必须使用所谓的应用程序服务器来处理 Python 中的 HTTP 请求。看这一个或尝试使用一些轻量级的Web框架,比如

The simplest web application in the Flask will look like this (in example, put it to app.pyfile):

Flask 中最简单的 Web 应用程序将如下所示(例如,将其放入app.py文件):

from flask import Flask
app = Flask(__name__)

@app.route("/test.py")  # consider to use more elegant URL in your JS
def get_x():
    x = 2
    return x

if __name__ == "__main__":
    # here is starting of the development HTTP server
    app.run()

Then you must start your server by doing:

然后您必须通过执行以下操作来启动您的服务器:

python app.py

By default it'll start on localhost:3000. Hence, you have to change urlin the JS code to http://localhost:3000/test.py.

默认情况下,它将从localhost:3000. 因此,您必须url将 JS 代码更改为http://localhost:3000/test.py.

UPD:Also note that the listed web servers are not production-ready. To build the production-ready configuration you can use something like uWSGI+nginxbinding.

UPD:另请注意,列出的 Web 服务器尚未做好生产准备。要构建生产就绪配置,您可以使用类似uWSGI+nginx绑定的方法。