【发布时间】:2020-05-10 18:09:57
【问题描述】:
(server.js)我有以下代码来运行我的服务器 -
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './public/index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('500 Internal Server error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(8000);
console.log('Server running at http://localhost:8000/');
(index.html) 我在公共目录中的 index.html 文件如下 -
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript" src="./algebra.js"></script>
<script type="text/javascript" src="./math.js"></script>
<script>
//Some more code ...
function runPythonCode(x, y){
//process python file and get result
}
runPythonCode(2, 3);
</script>
</body>
</html>
在runPythonCode 函数内的上述代码中,我想将变量x 和y 传递给我的python 代码并使用x 和y 进行一些处理,并希望将值返回给javascript。
我只是在 index.html 的脚本标签中尝试过这样的尝试,只是为了检查 python 脚本是否正在运行 -
text = "hello"
$.ajax({
type: "GET",
url: "./app.py",
//data: { param: text}
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
})
还有我的aap.py python 代码-
import csv
from numpy import matrix
def main():
x =2
return x
if __name__ == "__main__":
x=main()
但是在运行这段代码之后,我只是在控制台中获取了整个 python 代码。 我在这里做错了什么?如何在js中运行python文件?
【问题讨论】:
-
旁注:我有一个重大的安全问题,允许在未打包在沙箱中的服务器上运行任意用户代码。如果您想将其投入生产,您可能需要重新考虑您的方法。
-
@jbndlr 我可以稍后修改以用于生产目的我只是想试试这个东西是否可以做。
-
你不能像使用 PHP 一样使用 Python。你需要有一个正在运行的 Python Web 服务器,它带有一个可调用的 REST 端点,它将执行你的代码并通过 HTTP 返回结果。
-
@GorkaHernandez 好的。能否请您举例说明一下。
-
我不太熟悉创建一个具有这种行为的受过教育的示例,尽管这个指向 Python 文档的链接可能是一个好的开始:docs.python.org/2/library/simplehttpserver.html,你基本上需要像你一样创建一个 HTTP 服务器上面的 Node.js 已经完成了。
标签: javascript python html