[英]execute python script from javascript
I am a newbie to python. 我是python的新手。 I am working on a web app and trying to call a python script from a js script.
我正在开发Web应用程序,并尝试从js脚本调用python脚本。 I am using ajax to call the .py script as follows but I just keep getting the code returned in the response.
我正在使用ajax来按如下方式调用.py脚本,但我一直在获取响应中返回的代码。 For simplicity, I have reduced the computation in the python script - even the variable x is not being returned to the js file.
为简单起见,我减少了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 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。感谢您的帮助!
You have to use a so called application server to serve HTTP requests in Python. 您必须使用所谓的应用程序服务器来使用Python服务HTTP请求。 Look at this one or try to use some lightweight web frameworks like Flask .
看这一个或尝试使用一些轻量级的Web框架,比如瓶 。
The simplest web application in the Flask will look like this (in example, put it to app.py
file): 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
. 默认情况下,它将从
localhost:3000
开始。 Hence, you have to change url
in the JS code to http://localhost:3000/test.py
. 因此,您必须将JS代码中的
url
更改为http://localhost:3000/test.py
UPD: Also note that the listed web servers are not production-ready. UPD:还请注意,列出的Web服务器尚未投入生产。 To build the production-ready configuration you can use something like uWSGI+nginx binding.
要构建可用于生产环境的配置,您可以使用uWSGI + nginx绑定之类的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.