从 JS 调用 python 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32288722/
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
Call python function from JS
提问by Bahador Saket
I am trying to call a function in Python from my JavaScript code. I used the code explained herebut it does not work for me.
我试图从我的 JavaScript 代码中调用 Python 中的函数。我使用了此处解释的代码,但它对我不起作用。
Here is my JS code:
这是我的 JS 代码:
<!DOCTYPE html>
<body>
<script type="text/javascript" src="d3/d3.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
text ="xx";
$.ajax({
type: "POST",
url: "~/reverse_pca.py",
data: { param: text}
}).done(function(o) {
console.log(data);
console.log(text);
});
Python Code:
蟒蛇代码:
import csv
from numpy import genfromtxt
from numpy import matrix
def main():
...
return x
if __name__ == "__main__":
x=main()
return x;
Do you know what is wrong with it?
你知道它有什么问题吗?
采纳答案by Farshid T
Apart from the mentioned points and assuming you already have a proper setup to serve your python script and return the response. You should submit an asynchronous request, especially if the python code does some heavy computation.
除了提到的几点,并假设你已经有一个合适的设置来为你的 python 脚本提供服务并返回响应。您应该提交一个异步请求,尤其是当 Python 代码进行一些繁重的计算时。
function postData(input) {
$.ajax({
type: "POST",
url: "/reverse_pca.py",
data: { param: input },
success: callbackFunc
});
}
function callbackFunc(response) {
// do something with the response
console.log(response);
}
postData('data to process');
If you only do some light computation and you have no problem working with a code deprecated as of jQuery 1.8, go with the synchronous approach. This is not recommendedas it blocks the main thread.
如果您只进行一些轻量级计算,并且使用自 jQuery 1.8 起已弃用的代码没有问题,请使用同步方法。这不建议,因为它阻止主线程。
function runPyScript(input){
var jqXHR = $.ajax({
type: "POST",
url: "/reverse_pca.py",
async: false,
data: { param: input }
});
return jqXHR.responseText;
}
// do something with the response
response= runPyScript('data to process');
console.log(response);
Read more about it here: How do I return the response from an asynchronous call?and http://api.jquery.com/jquery.ajax/
在此处阅读更多相关信息:如何从异步调用返回响应?和http://api.jquery.com/jquery.ajax/
回答by Bahador Saket
After searching for few hours, I ended up having the following, and it worked well. Hope this helps someone else in future.
搜索了几个小时后,我最终得到了以下内容,并且效果很好。希望这有助于将来的其他人。
HTML and JS code: loging.html:
HTML 和 JS 代码:logging.html:
<html>
<head>
<title>Flask Intro - login page</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="static/bootstrap.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="http://code.jquery.com/jquery 2.1.4.min.js"></script>
</head>
<body>
<input id="submitbutton" type="submit" value="Test Send Data">
<!----------------------------------->
<script type="text/javascript">
function runPyScript(input){
var jqXHR = $.ajax({
type: "POST",
url: "/login",
async: false,
data: { mydata: input }
});
return jqXHR.responseText;
}
$('#submitbutton').click(function(){
datatosend = 'this is my matrix';
result = runPyScript(datatosend);
console.log('Got back ' + result);
});
</script>
Python code: app.py:
Python 代码:app.py:
from flask import Flask, render_template, redirect, url_for,request
from flask import make_response
app = Flask(__name__)
@app.route("/")
def home():
return "hi"
@app.route("/index")
@app.route('/login', methods=['GET', 'POST'])
def login():
message = None
if request.method == 'POST':
datafromjs = request.form['mydata']
result = "return this"
resp = make_response('{"response": '+result+'}')
resp.headers['Content-Type'] = "application/json"
return resp
return render_template('login.html', message='')
if __name__ == "__main__":
app.run(debug = True)