V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ohayoo
V2EX  ›  Python

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

  •  
  •   ohayoo · 234 天前 · 1072 次点击
    这是一个创建于 234 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位大佬,我今天用 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

    6 条回复    2023-09-06 20:17:10 +08:00
    ohayoo
        1
    ohayoo  
    OP
       234 天前
    AilF
        2
    AilF  
       234 天前   ❤️ 1
    用 yarl URL session.delete(URL(url, encoded=True)) 包一下就能拿到和 requests 一致的 url 了
    inkmulberry
        3
    inkmulberry  
       234 天前
    菜鸟理解:看样子是一个是冒号进行编码了一个是没有编码,直接把冒号用%3A 替换了
    ohayoo
        4
    ohayoo  
    OP
       234 天前
    @AilF #2 大佬 靠谱
    ochatokori
        5
    ochatokori  
       234 天前 via Android   ❤️ 1
    在 js 中,这是 encodeURI 和 encodeURIComponent 的区别,一个是会转义 uri 的保留字,一个不会,:就是 uri 保留字
    ohayoo
        6
    ohayoo  
    OP
       234 天前
    @ochatokori #5 涨知识了,多谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5612 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 06:42 · PVG 14:42 · LAX 23:42 · JFK 02:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.