【问题标题】:Run python code inside <script> tag of HTML file在 HTML 文件的 <script> 标记内运行 python 代码
【发布时间】: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 函数内的上述代码中,我想将变量xy 传递给我的python 代码并使用xy 进行一些处理,并希望将值返回给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


【解决方案1】:

有一个名为 brython 的工具,它允许您在 html 文件的脚本标签中添加 python 3 代码。

但是,我假设它通过将您的 python 代码转换为 javascript 并让浏览器使用它来工作。下面是一个 Python 脚本的示例:

<script type="text/python">
"""Code for the clock"""

import time
import math

from browser import document
import browser.timer

sin, cos = math.sin, math.cos
width, height = 250, 250 # canvas dimensions
ray = 100 # clock ray

background = "#111"
digits = "#fff"
border = "#333"

def needle(angle, r1, r2, color="#000000"):
    """Draw a needle at specified angle in specified color.
    r1 and r2 are percentages of clock ray.
    """
    x1 = width / 2 - ray * cos(angle) * r1
    y1 = height / 2 - ray * sin(angle) * r1
    x2 = width / 2 + ray * cos(angle) * r2
    y2 = height / 2 + ray * sin(angle) * r2
    ctx.beginPath()
    ctx.strokeStyle = "#fff"
    ctx.moveTo(x1, y1)
    ctx.lineTo(x2, y2)
    ctx.stroke()
</script>

【讨论】:

    【解决方案2】:

    浏览器支持的唯一客户端脚本语言是 JavaScript。 Python 不适合网络。

    如果您有兴趣在服务器端使用 python:https://www.djangoproject.com/

    【讨论】:

    • @iBug 我也尝试过 Flask,它也给出了相同的完整 python 代码作为响应。
    • @S.I.链接的哪一部分需要包含在答案中,如果我查看答案,链接本身似乎不需要任何内容​​
    【解决方案3】:

    您的 node.js HTTP 服务器配置为不执行 python 脚本;因此,它们以纯文本形式传递给调用者。

    在您的 node.js 服务器中,您可以使用 npm 模块来执行 python,如下所示:How to call python script from NodeJs

    但是,仍然被警告!永远不要执行来自您的网站访问者或可能被您的网站访问者更改的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多