Leeladharan Achar - alias - leelu ~ blogging...hola mi amigos..'s Blog

Posted Sept. 18, 2017   160 views

Python grequests Asynchronous Post Method Example

def get_async_web_response(url, method='GET', params=None, headers=None, encode=False, verify=None, use_verify=False, callback=None):
    import grequests
    # make a string with the request type in it:
    response = None
    request = None
    try:
        if 'POST' == method:
            if use_verify:
                request = grequests.post(url, data=params, headers=headers, verify=verify, callback=callback)
            else:
                request = grequests.post(url, data=params, headers=headers, callback=callback)
        else:
            request = requests.get(url, data=params, headers=headers, callback=callback)

        if request:
            response = grequests.send(request, grequests.Pool(1))
            return response
        else:
            return response
    except:
        return response

def printStatus(response, **kwargs):
    print "response code {}".format(response.status_code)
    print "response text {}".format(response.content)

params = {"name" : "morpheus", "job": "leader"}
headers = {'Content-type' : 'application/x-www-form-urlencoded'}

d = get_async_web_response('https://reqres.in/api/users', 'POST', params=params, headers=headers, callback=printStatus)
print("data posted")
if d:
    d.get()