venky4t venky4t -3 years ago 69
Python Question

POST request to URL with different JSON content executes successfully only for the last value of the file input

I have written a python script to read values from a text file individually and then do GET request to get data for each value from the URI. I am making a change to the data and will POST data to the same URI.

However, the issue I am facing here is :
1. If I use 10 values in the input file first 9 values give 500 server error and the last one executes successfully with Response 200 OK and successfully updates data.
2. When I remove the last value and run it again, same repeats(8 failed with 500 and 1 success with 200 OK). This repeats for any number of values.
3. Script always runs successfully for one input value.

Please check the script and help.

#!/usr/bin/python


import sys
import requests
import json

POSTAPI_PROD = URI here(not mentioned since public forum)
POSTAPI_HEADERS = headers here

#returns the POST response code for each value from payload data
def post_response_with_value(post_payload):
responsePost = requests.post(POSTAPI_PROD,headers = POSTAPI_HEADERS,data=post_payload)
print(responsePost)

#replaces the intended data for each value from payload data
def replace_data_with_value(payload_data):
post_payload = "replace function here" //works fine
print "replace success"
post_response_with_value(post_payload)

#get the response for each value.Invokes replace method
def get_resposne_with_value(value):
#input_url="URL/%s" % value
response = requests.request("GET",input_url)
print(response.status_code)
json_response=json.loads(response.text)
payload=json.dumps(json_response['payload'])
replace_data_with_value(payload)

#reads values from input file.Invokes for 'GET' responses for each value
def read_input_file_with_value():
with open('file.txt', 'r') as data:
for value in data:
get_resposne_with_value(value)
print "read file is success"

read_input_file_with_value()

Answer Source

try to remove , \r \n

for value in data:
    clean_value = value.rstrip()
    get_resposne_with_value(clean_value)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download