requests 模块和 aiohttp 发送的请求, urlencode 为啥会有这个区别

248 天前
 ohayoo

各位大佬,我今天用 requests 模块调接口正常,用 aiohttp 模块调接口出问题,排查发现是 aiohttp 发送请求时的 urlencode 和 requests 的不一样,具体如下,请问下大佬们,这个要如何处理呢?

url = "http://api.baidu.com/test-files/testFiles/1234/%E9%97%AE%E9%A2%98%E5%8D%95%E6%97%B6%E6%95%88-%E8%B7%9F%E8%BF%9B_2020-04-02%2000%3A00%3A00_2020-04-08%2000%3A00%3A00_5675.xlsx.zip"

def delete_url1(url):
    r = requests.delete(url)
    print(f"requests 模块请求地址为:{r.url}")

delete_url1(url)

print()

async def delete_url2(url):
    async with aiohttp.ClientSession() as session:
        async with session.delete(url) as resp:
            print(f"aiohttp 模块请求地址为:{resp.url}")

asyncio.run(delete_url2(url))

执行结果: requests 模块请求地址为: http://api.baidu.com/test-files/testFiles/1234/%E9%97%AE%E9%A2%98%E5%8D%95%E6%97%B6%E6%95%88-%E8%B7%9F%E8%BF%9B_2020-04-02%2000%3A00%3A00_2020-04-08%2000%3A00%3A00_5675.xlsx.zip

aiohttp 模块请求地址为: http://api.baidu.com/test-files/testFiles/1234/%E9%97%AE%E9%A2%98%E5%8D%95%E6%97%B6%E6%95%88-%E8%B7%9F%E8%BF%9B_2020-04-02%2000:00:00_2020-04-08%2000:00:00_5675.xlsx.zip

1085 次点击
所在节点    Python
6 条回复
ohayoo
248 天前
AilF
248 天前
用 yarl URL session.delete(URL(url, encoded=True)) 包一下就能拿到和 requests 一致的 url 了
inkmulberry
248 天前
菜鸟理解:看样子是一个是冒号进行编码了一个是没有编码,直接把冒号用%3A 替换了
ohayoo
248 天前
@AilF #2 大佬 靠谱
ochatokori
248 天前
在 js 中,这是 encodeURI 和 encodeURIComponent 的区别,一个是会转义 uri 的保留字,一个不会,:就是 uri 保留字
ohayoo
248 天前
@ochatokori #5 涨知识了,多谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/971502

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX