我将在Scrapy下载器中间件中使用一些阻塞代码(等待免费代理)。 我打算使用this method
但是它在downloadermiddleware中确实不起作用,因为方法 process_request(self, request, spider)
等待isinstance(response, (Response, Request))
如何最好地做到这一点?
最佳答案
您可以使用扭曲方法“deferToThread”来运行阻塞代码而不阻塞MainThread
from twisted.internet.threads import deferToThread
class DownloaderMiddleware:
def process_request(self, request, spider):
return deferToThread(self.run_blocking_code_in_diffrent_thread, request, spider)
def run_blocking_code_in_diffrent_thread(self,request, spider) -> HtmlResponse:
print("Code will block here on a diffrent thread and wont stop MainThread")
request.meta["proxy"] = get_proxy_blocking_call()
return request
关于python - 在Scrapy下载器中间件中使用Deferred,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26711309/