0

拥有多个有效负载字典,如何更好地创建格式化 url 列表,以便 grequest 可以迭代?

payload_single: {'search': '51 F ST SW,AUBURN KING 98001,WA,USA', 'app_code': 'xyz', 'app_id': 'xyz', 'lod': '9'}

payload_single: {'search': '55 F ST SW,AUBURN KING 98001,WA,USA', 'app_code': 'xyz', 'app_id': 'xyz', 'lod': '9'}

为了能够使用以下代码通过遍历 URLS 的 grequests 发送请求:

unsentrequests=(grequests.get(u, hooks = {'response' : do_something}) for u in urls) 
responses=grequests.map(unsentrequests)

对于请求的单个调用,我会使用这个:

row = requests.get(url_single, params=payload_single)

编辑 1 @rebeling

    for url in urls:
        unsent_request.append(grequests.get(url_single,
                                        hooks={'response': resphandler()},
                                        params=url))

def resphandler():
    rs = grequests.map(unsent_request)

    for r in rs:
        print r
4

1 回答 1

1
import grequests  

def do_something(response, *args, **kwargs):  
    print response  


payloads = [
    {'search': '51 F ST SW,AUBURN KING 98001,WA,USA', 'app_code': 'xyz', 'app_id': 'xyz', 'lod': '9'},
    {'search': '55 F ST SW,AUBURN KING 98001,WA,USA', 'app_code': 'xyz', 'app_id': 'xyz', 'lod': '9'}]

unsent_request = []  

请参阅 grequests 代码第 35 行:接受与请求相同的参数Session.request和一些附加参数,因此我们像在请求中一样使用参数。

for payload_single in payloads:
    unsent_request.append(grequests.get('http://www.google.com', 
                                        hooks={'response': do_something}, 
                                        params=payload_single))

print grequests.map(unsent_request)
于 2015-09-29T19:28:48.763 回答