我有一个RequestHandler
类,该类将被实例化并传递给所有客户端,客户端将通过handle_new_request
方法向其发送请求。 RequestHandler
也应该能够独立执行这些请求。
下面的请求看起来很普通,但是在服务于该请求的应用程序中可能要花一些时间,因此我想异步执行这些请求。
from collections import deque
import time
class Request:
"""
Naive implementation of a request class.
"""
def __init__(self, req_name: str):
self.req_name = req_name
class RequestsHandler:
"""
Implementation for a naive requests handler class that accepts
requests from clients and serves them via a ThreadPool.
"""
def __init__(self, max_working_threads:int = 5):
self.max_working_threads = max_working_threads
self.request_queue = deque()
def handle_new_request(self, new_req: Request):
"""
Puts the new request made by a client into the request_queue.
:param new_req: Request made.
:return: None
"""
self.request_queue.append(new_req)
def serve_request(self):
"""
Pops a new request from the request queue and serves it.
:return: None
"""
new_request: Request = self.request_queue.popleft()
time.sleep(5)
print('served request %s'%new_request.req_name)
类handle_new_request
的 serve_request
和RequestHandler
方法应该异步工作,而对象应该
即使队列为空,也可以存活。