Python 在Get上运行脚本并立即返回响应

Python 在Get上运行脚本并立即返回响应,python,basehttpserver,Python,Basehttpserver,很抱歉,我对Python httpserver非常不熟悉。我也知道它的弱点或局限性,但它非常适合我的需要 根据请求头中的内容,我有大约10行代码运行在服务器的每个get请求上。这些可能需要8个小时才能完全运行,但我想立即返回请求的响应。这样做的最佳方法是什么 from http.server import BaseHTTPRequestHandler, HTTPServer import logging class S(BaseHTTPRequestHandler): def _se

很抱歉,我对Python httpserver非常不熟悉。我也知道它的弱点或局限性,但它非常适合我的需要

根据请求头中的内容,我有大约10行代码运行在服务器的每个get请求上。这些可能需要8个小时才能完全运行,但我想立即返回请求的响应。这样做的最佳方法是什么

from http.server import BaseHTTPRequestHandler, HTTPServer
import logging


class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        THIS IS WHERE MY CODE IS RUNNING
        logging.info("GET request,nPath: %snHeaders:n%sn", str(self.path), str(self.headers))
        self._set_response()
        self.wfile.write("HEY A GET request for {}".format(self.path).encode('utf-8'))


def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...n')


if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()


谢谢

这正是多线程的用途,我建议您阅读本文以了解更多信息

下面是如何从do_GET函数内部创建新线程的示例:

from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import thread


class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

def do_process(self):
# Your code here

def do_GET(self):
    thread.start_new_thread(self.do_process)
    logging.info("GET request,nPath: %snHeaders:n%sn", str(self.path), str(self.headers))
    self._set_response()
    self.wfile.write("HEY A GET request for {}".format(self.path).encode('utf-8'))


def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...n')


if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

谢谢,我去看看。它会立即返回响应吗?是的,因为do_进程函数将在不同的线程中运行,并且不会阻止do_GET函数的执行