0

我目前正在寻找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())
4

1 回答 1

4

你只能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,您可以使用异步列表/设置/等理解

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)
于 2017-03-04T15:38:34.747 回答