运行 python 后台脚本或 web worker

Run python script in background or web worker

我想 运行 一个 python 代码来解决浏览器中的一些方程式。我目前在网络工作者中使用 javascript 执行此操作。这根本不与 DOM 交互,它只是接收一些输入,进行一些计算,然后 returns 输出。我希望能够以同样的方式使用 python。这可能吗?

我认为您无法让客户端的浏览器执行任何 Python 代码。您必须想出某种协议来与 Python 来回通信。一种常见的方法是在某处设置一个 Python 进程 运行 作为 HTTP(s) 服务器。您可以让客户端的浏览器对 Python 服务器进行 API 调用(某种形式的 HTTP 请求),然后那段单独的 Python 代码 运行 将捕获该调用并且发回数据。这可以像 标记或一些 Javascript 代码一样简单,它可以发出请求并在浏览器中解释响应。

试试这个,进入一个新目录并创建两个文件。

server.py(基于 python3):

#!/usr/bin/env python

import http.server
import logging

IP = '127.0.0.1'
PORT = 8001

class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        url = self.path
        headers = self.headers
        print('received request:', url)

        numbers = url.split('/')
        print('parsed numbers:', numbers)
        try:
            sumTotal = 0
            for num in numbers:
                if num == '':
                    continue
                sumTotal += int(num)
            self.respond(sumTotal)
        except ValueError as ex:
            logging.error('unable to parse value: %s' % num)
            self.respond(-1)

    def respond(self, sumTotal):
        # Send response status code
        self.send_response(200)

        # Send headers
        self.send_header('Content-type','text/html')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()

        # Send message back to client
        message = str(sumTotal)
        # Write content as utf-8 data
        self.wfile.write(bytes(message, 'utf8'))
        return

def main():
    address = (IP, PORT)
    httpd = http.server.HTTPServer(address, MyHandler)
    httpd.serve_forever()

if __name__ == '__main__':
    main()

test.html:

<!DOCTYPE HTML>
<html lang="en-us">
<head>
  <title>Python Linking Demo</title>
  <script type="text/javascript">

    function addNumbers(a, b) {
      var url = 'http://localhost:8001/' + a + '/' + b;
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          var data = xhr.responseText;
          var el = document.getElementById('data-div');
          if (!el) {
            return;
          }
          el.innerHTML = data;
        }
      }
      xhr.open('GET', url, true);
      xhr.send(null);
    };

    setTimeout(function(){addNumbers(7, 13);}, 1000);

  </script>
</head>
<body>
  <h1>With some luck, this will populate below:</h1>
  <div id="data-div">{{number}}</div>
</body>
</html>

现在,首先为 Python 进程启动服务器:

$ python server.py

虽然那是 运行,但也启动 Web 服务器来为 html(也就是 python3)提供服务:

$ python -m http.server 8000

然后尝试将浏览器导航至 http://localhost:8000/test.html and you should see test.html make a request to http://localhost:8001/7/13 which will invoke the Python method MyHandler.do_GET() which sends back an HTTP response containing the sum of the numbers, 20. Credit goes to this website which I basically copy-pasted from: https://daanlenaerts.com/blog/2015/06/03/create-a-simple-http-server-with-python-3/

这是尽可能简单和原始的,它对一两个功能非常有用,但如果您发现自己将大量功能导出到 Python,则值得升级到更高级的图书馆和框架(在 client/Javascript 和 server/Python 方面)打算更健壮和功能完整来做这类事情。