Python 3.5 异步关键字

Python 3.5 async keyword

我目前正在研究 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())

您只能在 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)

pulsar 内部使用 asyncio,所以你不必显式导入它来使用它,通过 pulsar 使用它


作为旁注,如果您升级到 python 3.6,您可以使用异步 list/set/etc 理解

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)