如何将参数传递给python grequests中的钩子 [英] How to pass parameters to hooks in python grequests

查看:92
本文介绍了如何将参数传递给python grequests中的钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据请求文档,可以将事件挂钩添加到 .get() 函数.

According the Requests documentation, event hooks can be added to .get() function.

requests.get('http://httpbin.org', hooks=dict(response=print_url))
def print_url(r, *args, **kwargs):
    print(r.url)

这很好,但是如何使用自定义参数设置 *args,例如,我想将一些自定义值传递给 print_url(),如何在 *args 中设置这些值?这样的事情失败了:

This is fine but how to set *args with custom parameters, for example, I want to pass some custom values to print_url(), how to set those in *args ? Something like this fails :

args = ("search_item", search_item)
rs = (grequests.get(u, hooks={'response': [parse_books],'args': [args]}) for u in urls)

推荐答案

您不能指定要传递给响应挂钩的额外参数.如果你想指定额外的信息,你应该创建一个你调用的函数,然后返回一个作为钩子传递的函数,例如,

You cannot specify extra arguments to pass to a response hook. If you want extra information to be specified you should make a function that you call which then returns a function to be passed as a hook, e.g.,

def hook_factory(*factory_args, **factory_kwargs):
    def response_hook(response, *request_args, **request_kwargs):
        # use factory_kwargs
        # etc.
        return None # or the modified response
    return response_hook

grequests.get(u, hooks={'response': [hook_factory(search_item=search_item)]})

这篇关于如何将参数传递给python grequests中的钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆