如何检查响应类型 aiohttp asyncio python
how to check response type aiohttp asyncio python
我有以下方法:
async def make_request(self, url):
async with aiohttp.ClientSession() as session:
async with self.limit, session.get(url=url) as response:
resp = await response.read()
await asyncio.sleep(self.rate)
return resp
如何检查resp
是否包含json
?这样我就可以在 json
中格式化,例如json.dumps(resp)
也许吧?如果 resp 类型是 html
那么我将不得不遍历 html 树来提取 resp value
我试过:
async def make_request(self, url):
async with aiohttp.ClientSession() as session:
async with self.limit, session.get(url=url) as response:
resp = await response.json()
await asyncio.sleep(self.rate)
return resp
但是如果 resp
包含 html
就会出错
如上所述检查Content-Type
header应该是第一步;但是,如果由于任何原因 header 丢失或不正确,您可以随时使用:
text = await response.text()
try:
data = json.loads(text)
except ValueError as exc:
print("cannot parse JSON: %s" % exc)
# use text value
我有以下方法:
async def make_request(self, url):
async with aiohttp.ClientSession() as session:
async with self.limit, session.get(url=url) as response:
resp = await response.read()
await asyncio.sleep(self.rate)
return resp
如何检查resp
是否包含json
?这样我就可以在 json
中格式化,例如json.dumps(resp)
也许吧?如果 resp 类型是 html
那么我将不得不遍历 html 树来提取 resp value
我试过:
async def make_request(self, url):
async with aiohttp.ClientSession() as session:
async with self.limit, session.get(url=url) as response:
resp = await response.json()
await asyncio.sleep(self.rate)
return resp
但是如果 resp
包含 html
如上所述检查Content-Type
header应该是第一步;但是,如果由于任何原因 header 丢失或不正确,您可以随时使用:
text = await response.text()
try:
data = json.loads(text)
except ValueError as exc:
print("cannot parse JSON: %s" % exc)
# use text value