我目前正在研究pulsar
的异步HTTP客户端。
以下示例位于文档中:
from pulsar.apps import http
async with http.HttpClient() as session:
response1 = await session.get('https://github.com/timeline.json')
response2 = await session.get('https://api.github.com/emojis.json')
但是当我尝试执行它时,我得到了
async with http.HttpClient() as session:
^ SyntaxError: invalid syntax
看起来无法识别async
关键字。我使用的是Python 3.5。
工作示例:
import asyncio
from pulsar.apps.http import HttpClient
async def my_fun():
async with HttpClient() as session:
response1 = await session.get('https://github.com/timeline.json')
response2 = await session.get('https://api.github.com/emojis.json')
print(response1)
print(response2)
loop = asyncio.get_event_loop()
loop.run_until_complete(my_fun())
答案 0 :(得分:4)
你只能在coroutines内使用async with
,所以你必须这样做
from pulsar.apps.http import HttpClient
import pulsar
async def my_fun():
async with HttpClient() as session:
response1 = await session.get('https://github.com/timeline.json')
response2 = await session.get('https://api.github.com/emojis.json')
return response1, response2
loop = pulsar.get_event_loop()
res1, res2 = loop.run_until_complete(my_fun())
print(res1)
print(res2)
内部脉冲星使用asyncio,因此您无需明确导入它以使用它,通过脉冲星使用它
作为旁注,如果升级到python 3.6,则可以使用异步列表/设置/等理解
from pulsar.apps.http import HttpClient
import pulsar
async def my_fun():
async with HttpClient() as session:
urls=['https://github.com/timeline.json','https://api.github.com/emojis.json']
return [ await session.get(url) for url in urls]
loop = pulsar.get_event_loop()
res1, res2 = loop.run_until_complete(my_fun())
print(res1)
print(res2)