2017-03-04 63 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