【问题标题】:Python 3.5 async keywordPython 3.5 异步关键字
【发布时间】:2017-07-24 15:53:27
【问题描述】:

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

【问题讨论】:

  • 你确定确定你使用的是python 3.5吗?
  • $ python3 Python 3.5.2(默认,2016 年 11 月 17 日,17:05:23)
  • 试试from pulsar.apps.http import HttpClientasync with HttpClient()看看错误是否改变。
  • 触发上述错误的具体命令是什么?
  • @BrandonIbbotson 我按照建议尝试,得到相同的错误异步 with HttpClient() as session: 我标记了 ^ 的位置

标签: python python-3.x asynchronous python-pulsar


【解决方案1】:

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

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)

【讨论】:

  • 我添加了一个有效的解决方案,有没有办法在没有异步事件循环的情况下做到这一点,或者这是正确的方法吗?
  • 如果我理解正确的话,它们是 intendedasyncio 一起使用,但是任何其他支持协程的库都应该可以正常工作,我认为...
  • 你也可以通过 pulsar 使用 get_event_loop
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多