简体   繁体   中英

Extract elements one by one from list and pass to request payload

I have list which contains 100 elements. I am iterating over the list, and getting the elements. But it gives me all the elements in one go.

# list of elements
list = ["apple is a fruit", "spinach is a vegetable", "python is fun", .... ,"100th element"]

#for each element in the list, iterate the list
for elements in list:
    # print the element
    print(elements)

I was wondering if there is a way, I could extract the first element , pass it as request body for a REST API call, get the response.

Sample :

    payload = {
        "country": "India",
        "elements": firstElementFromList
    }

    response = requests.post(http://www.test-url.com, json=payload)

Once the response is received, extract the second element from list , pass it as request body for REST API call to the same end-point and get the response. Repeat the activity, till 100'th element is extracted and is passed as request body for the REST call.

Note : I tried passing elements to the payload but it passes all the elements in one go.

Any pointers/help on how to achieve similar implementation is really appreciable.

Thanks a ton in advance!

I think this should work

import asyncio
async def insert(element):
    payload = {
        "country": "India",
        "elements": element
    } 
    response = requests.post(http://www.test-url.com, json=payload)
for element in list:
    try:
        await insert(element) 
    except:
        print("Problem occurred at element", element)
        break

If I understand you correctly you want to process the elements sequentially? Then it should be as easy as this:

import requests


list = ["apple is a fruit", "spinach is a vegetable", "python is fun","100th element"]

for elements in list:
    print(elements)
    payload = {
        "country": "India",
        "elements": elements
    }
    response = requests.post("http://www.test-url.com", json=payload)
    print(response)

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