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
w9ay
V2EX  ›  Python

[ Python ] 为什么 requests hook 失败了

  •  
  •   w9ay · 2019-07-30 18:08:56 +08:00 · 1654 次点击
    这是一个创建于 1725 天前的主题,其中的信息可能已经有所发展或是发生改变。

    requests 默认会对 url 的参数进行转义,我看了一下源码,问题出现在 requests.utils 的 requote_uri 中,所以我尝试 hook 这个函数。

    from urllib.parse import quote
    
    import requests
    
    
    def hook2(uri):
        print(11111111)
        safe_with_percent = "!#$%&'()*+,/:;=?@[]~{}^"
        return quote(uri, safe=safe_with_percent)
    
    
    requests.utils.requote_uri = hook2
    requests.get("http://127.0.0.1:8000", params='a=111&b=222!@$%^&({}')
    

    主要是对{}符号的转义,我想知道为什么这样不行呢?

    4 条回复    2020-07-30 22:48:00 +08:00
    keakon
        1
    keakon  
       2019-07-30 18:49:31 +08:00   ❤️ 1
    models.py 里执行了 from .utils import requote_uri,你再去修改 requests.utils.requote_uri,不会对 models.py 里的 requote_uri 有任何影响。
    w9ay
        2
    w9ay  
    OP
       2019-07-31 13:27:12 +08:00
    @keakon 感谢回复,那有什么方法来 hook 它吗?
    keakon
        3
    keakon  
       2019-07-31 14:01:52 +08:00
    一个是在 import model 之前修改,另一个是修改 model.requote_uri
    lisongee
        4
    lisongee  
       2020-07-30 22:48:00 +08:00
    @keakon import 之前怎么修改?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1706 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:39 · PVG 00:39 · LAX 09:39 · JFK 12:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.