gpt4 book ai didi

具有多线程响应处理程序的 Python http 服务器

转载 作者:可可西里 更新时间:2023-11-01 17:02:35 25 4
gpt4 key购买 nike

我正在尝试设置一个处理 POST 数据包的 python 服务器。数据包到达后,do_POST 会启动一个包含自身和一些数据的新线程,然后,线程做一些事情并将接收到的输出放入 self 对象中。这是我到目前为止所拥有的:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
....
class httpHandler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers['content-length'])
data = self.rfile.read(length)
Resolver(self,data).start()
return

然后,在我的解析器类中,我会:导入线程

class Resolver(threading.Thread):
def __init__(self,http,number):
threading.Thread.__init__(self)
self.http = http
self.number = number + "!"

def run(self):
self.http.send_response(200)
self.http.send_header('Content-type','text/html')
self.http.send_header('Content-length', len(self.number))
self.http.end_headers()
# Send the html message
self.http.wfile.write(self.number)
return

当然,这是一个示例而非完整的表格,我仍处于测试我的程序的阶段。它将在一个薄弱的平台(目前是 Raspberry pi)上运行,我正在寻找一个良好的性能解决方案。有什么建议吗?

最佳答案

问题是 BaseHTTPRequestHandler 期望您在从 do_POST 返回时完成请求。这在文档中并不是那么清楚,但如果您查看 handle_one_request 的源代码,它会立即显而易见。 ,调用你的方法的方法:

mname = 'do_' + self.command
# ...
method = getattr(self, mname)
mname()
self.wfile.flush() #actually send the response if not already done.

如果你看得更深,你会发现,正如你所期望的,代码希望能够在处理完请求后立即关闭或重用连接。

因此,您不能以这种方式使用 BaseHTTPRequestHandler

当然,您也可以编写自己的处理程序实现。在很大程度上,BaseHTTPServer 中的内容更像是示例代码,而不是一个强大、高效、健壮和灵活的框架(这就是文档直接链接到源代码的原因)。

或者,不是尝试为每个请求创建一个线程,而是为每个连接创建一个线程。 ThreadingMixIn类使这变得容易。

但更好的解决方案是使用更好的框架,例如 Twisted 或 Tornado,或者使用为您执行线程并仅通过 WSGI 调用您的代码的网络服务器。

关于具有多线程响应处理程序的 Python http 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com