I have code like this:
import requests
from multiprocessing import Pool
import json
import time
from datetime import datetime as dt
BASE_URL = 'http://localhost:3000/test'
with open('data.json', 'r') as f:
list_dict = json.load(f)
def resource_post(post_data):
stuff_got = []
timestamp = dt.now().strftime('%Y%m%d %H:%M:%S:%f')[:-3] # timestamp
post_data["timestamp"] = timestamp
response = requests.post(BASE_URL, json=post_data)
stuff_got.append(response.json())
print(stuff_got) # print hasil response
df = pd.DataFrame.from_dict(stuff_got)
df.to_csv("output.txt", sep='|', mode='a', index=False, header=False)
#time.sleep(0.1) #delay
return stuff_got
if __name__ == '__main__':
start=time.time()
pool = Pool()
with pool as p:
p.map(resource_post,list_dict)
p.close()
p.join()
elapsed = (time.time() - start)
print("\n","time elapsed is :", elapsed)
in file data.json:
[{"first_name":"John","last_name":"Swen"},{"first_name":"Ricard","last_name":"Candra"}]
in BASE_URL there is data like this:
{
"body": {
"first_name": "Sebastian",
"last_name": "Eschweiler"
}
I want to post dictionary from data.json with the format:
{
"body": {
"first_name":"John",
"last_name":"Swen"
}
}
each data above will be looped, and will generate response {"responseCode": "0006", "responseMessage": "success", "first_name": "John"} from the server. I will enter the response into the output.txt file with the format:
0006 | success | John.
so how to make each dictionary in data.json will be posted to the server with the format:
{
"body": {
"first_name":"John",
"last_name":"Swen"
}
}