toy script显示一个应用程序使用的类依赖于不支持asyncio的实现,显然不起作用。
如何使用支持asyncio的客户端实现MyFetcher的fetch方法,同时仍然使用FetcherApp的_internal_validator方法维护合同?要非常清楚,不能修改FetcherApp和AbstractFetcher。
答案 0 :(得分:1)
要在fetch_data
fetch
内使用异步fetch
功能,is_fetched_data_valid
和import asyncio
class AsyncFetcherApp(FetcherApp):
async def is_fetched_data_valid(self): # async here
data = await self.fetcher_implementation.fetch() # await here
return self._internal_validator(data)
class AsyncMyFetcher(AbstractFetcher):
def __init__(self, client):
super().__init__()
self.client = client
async def fetch(self): # async here
result = await self.client.fetch_data() # await here
return result
class AsyncClient:
async def fetch_data(self):
await asyncio.sleep(1) # Just to sure it works
return 1
async def main():
async_client = AsyncClient()
my_fetcher = AsyncMyFetcher(async_client)
fetcherApp = AsyncFetcherApp(my_fetcher)
# ...
is_valid = await fetcherApp.is_fetched_data_valid() # await here
print(repr(is_valid))
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
函数也应该是异步的。您可以在没有修改父级的子类中更改它们:
ProcessName