2017-03-04 83 views
0

我目前正在调查pulsar的异步HTTP客户端。Python 3.5异步关键字

下面的例子是在文档:

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

你绝对_certain_你使用Python 3.5? – byxor

+0

$ python3 Python 3.5.2(默认,2016年11月17日,17:05:23) – Markus

+0

尝试'从pulsar.apps.http导入HttpClient'和'使用HttpClient()异步'来查看错误是否更改。 – byxor

回答

4

你只能使用一个async with里面coroutines,所以你必须要做到这一点

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) 
+0

我添加了一个工作的解决方案,有没有办法做到这一点,没有asyncio事件循环,或者这是正确的方式? – Markus

+0

如果我理解正确,他们[用于](https://docs.python.org/3/whatsnew/3.5.html#pep-492-coroutines-with-async-and-await-syntax)与[asyncio](https://docs.python.org/3/library/asyncio.html#module-asyncio),但任何其他支持协程的库应该工作得很好,我认为... – Copperfield

+0

也可以使用get_event_loop通过脉冲星 – Copperfield