3

I want to make my code Async for HTTP calls, since the whole program stops while the call is being made.

I took a look at grequests and couldn't figure it out, same for asyncio

this is the current sync version of the code:

myvar1 = class_object()

response = requests.get(myvar1.url)

if response.status_code == 200:
    myvar1.accept()

I would like to do the following instead:

def myfunction:

    request.get(myvar1.url,callbackfunction(response,myvar1))

    return None

def callbackfunction(response,myvar1):

    if response.status_code == 200:
        myvar1.accept()

I can successfully pass a callback function to the request, the question is how to pass arguments to that callback.

Basically, the goal is to execute a method of the passed argument of the callback function.

felartu
  • 92
  • 1
  • 8
  • 1
    Possible duplicate of [Does python-requests have any callback method?](https://stackoverflow.com/questions/31095006/does-python-requests-have-any-callback-method) – quamrana May 16 '19 at 20:12
  • I can successfully pass a callback function to the request, the question is how to pass arguments to that callback. – felartu May 16 '19 at 20:26
  • Does this answer your question? [Python, how to pass an argument to a function pointer parameter?](https://stackoverflow.com/questions/13783211/python-how-to-pass-an-argument-to-a-function-pointer-parameter) – user202729 Aug 15 '21 at 06:26

1 Answers1

3

Lets make a partial function:


def myfunction(var, func):

    request.get(var.url, callback =  func)


def callbackfunction(response, var):

    if response.status_code == 200:
        var.accept()

# Now make a partial function to wrap callbackfunction
def wrapper(var):
    def callback(response):
        callbackfunction(response, var)
    return callback

myvar1 = class_object()

myfunction(myvar1, wrapper(myvar1))

So, requests.get() will eventually call func(response) which in fact will be callback(response) which calls callbackfunction(response, myvar1)

quamrana
  • 37,849
  • 12
  • 53
  • 71