简体   繁体   中英

Proper syntax of parameters using function run_in_executor()

To make a POST call to the API, I use the following script:

r = requests.post(
    url,
    headers={
        "Content-Type": "application/json"
    },
    json={
        "email": my_email,
        "password": my_password
    }
)

and everything works. Now, I want to rewrite this code as a parameter to the function run_in_executor() . I did it in the following way but didn't get the desired results:

data1 = dict(
    headers={
        "Content-Type": "application/json"
    },
    json={
        "email": my_email,
        "password": my_password
    }
)

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(
        None,
        requests.post,
        url,
        data1
    )
    # rest of the code

In fact, I get an error that tells me that it is mandatory to enter email and password, so obviously I am doing something wrong in passing the parameters. Printing response = await future1 I get error 422. Can anyone help me?

Sadly, run_in_executor does not support keyword arguments.

You may use functools.partial to pack all arguments into one callable and pass it to run_in_executor .

from functools import partial

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(
        None,
        partial(
            requests.post,
            url,
            headers={
                "Content-Type": "application/json"
            },
            json={
                "email": my_email,
                "password": my_password
            }
        ),
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM