2017-08-26 80 views
1

我正在開發一個程序。它從文件讀取URL,然後發出請求。但處理程序不會被調用。異步請求不能使用GRequests

這裏是我的代碼:

import grequests 


def main(): 
    async_list =[] 

    for site in extractsites(): 
     action_item = grequests.get('http://' + site, hooks={'response': handleresponse}) 
     async_list.append(action_item) 

    grequests.map(async_list) 


def extractsites(): 
    return ['google.com'] 


def handleresponse(response): 
    print(response) 


if __name__ == '__main__': 
    main() 

誰能明白爲什麼它不工作?

回答

1

處理程序必須有不同的簽名,其他參數可以通過:

def handler(response, **kwargs): 
    print(response, kwargs) 

完整的示例:

import grequests 

def main(): 
    async_list =[] 

    for site in extractsites(): 
     action_item = grequests.get('http://' + site, hooks={'response': handleresponse}) 
     async_list.append(action_item) 

    grequests.map(async_list) 

def extractsites(): 
    return ['google.com'] 

def handleresponse(response, **kwargs): 
    print(response, kwargs) 

if __name__ == '__main__': 
    main() 

或更短:

import grequests 
urls = ['http://google.com'] 
handler = lambda response, **kwargs: print(response, kwargs) 
grequests.map(grequests.get(url, hooks={'response': handler}) for url in urls) 
+0

仍然無法正常工作,只是檢查, – zython

+1

@zython,以及我檢查,它的工作原理,我會粘貼一個例子在分鐘 –

+0

是的,你的作品,我會用你的建議 – zython