aiohttp:如何发出简单的http请求
aiohttp: how to make simple http request
我正在探索异步 http 请求的 aiohttp。
aiohttp 上的客户端快速入门 website 建议将此代码作为最小示例:
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
对我来说 python 3.6.5 这导致
async with aiohttp.ClientSession() as session:
SyntaxError: invalid syntax
我是不是遗漏了什么?
感谢任何帮助!谢谢。
编辑:
我在做测试。首先我意识到我需要 python 3.7。
所以我切换了,现在错误消息是:
async with aiohttp.ClientSession() as session:
SyntaxError: 'async with' outside async function
不是Python版本的问题:aiohttp支持Python>=3.5.3,所以3.6.5绝对没问题。但请注意错误信息:
SyntaxError: 'async with' outside async function
就是这样:您只能在异步函数中使用 async with
:
import aiohttp
import asyncio
async def start():
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
loop = asyncio.get_event_loop()
loop.run_until_complete(start())
该消息对于 Python 3.5 和 3.6 也是正确的,它们只是在 3.7
中变得更加友好
我正在探索异步 http 请求的 aiohttp。
aiohttp 上的客户端快速入门 website 建议将此代码作为最小示例:
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
对我来说 python 3.6.5 这导致
async with aiohttp.ClientSession() as session:
SyntaxError: invalid syntax
我是不是遗漏了什么?
感谢任何帮助!谢谢。
编辑:
我在做测试。首先我意识到我需要 python 3.7。 所以我切换了,现在错误消息是:
async with aiohttp.ClientSession() as session:
SyntaxError: 'async with' outside async function
不是Python版本的问题:aiohttp支持Python>=3.5.3,所以3.6.5绝对没问题。但请注意错误信息:
SyntaxError: 'async with' outside async function
就是这样:您只能在异步函数中使用 async with
:
import aiohttp
import asyncio
async def start():
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
loop = asyncio.get_event_loop()
loop.run_until_complete(start())
该消息对于 Python 3.5 和 3.6 也是正确的,它们只是在 3.7
中变得更加友好