立即在获取和返回响应上运行脚本



抱歉,但我对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()

相关内容

  • 没有找到相关文章

最新更新