Reputation: 5
The Host value int he URL will be passed as arguments but when i print the URL , it is working fine but not executing properly as whole script.
Python script:
import requests
import json
import urllib
import sys
import os
host=(str(sys.argv[1]))
headers={
"accept": "application/json",
"content-type": "application/json"
}
test_urls = 'https://{host}/Thingworx/Things/PG.MonitorStats.Stream/Services/GetStreamData?maxItems=1&oldesFirst=false&appKey=0b858f3f-4ed0-499c-a4d2-9ad0fbc0da9b&method=post'.format(host=host)
print (test_urls)
def return_json(url):
try:
response = requests.get(url,headers=headers)
# Consider any status other than 2xx an error
if not response.status_code // 100 == 2:
return "Error: Unexpected response {}".format(response)
json_obj = response.json()
return json.dumps(json_obj)
except requests.exceptions.RequestException as e:
# A serious problem happened, like an SSLError or InvalidURL
return "Error: {}".format(e)
for url in test_urls:
print return_json(url).format(host=host)
Error Output:
Error: Invalid URL 'h': No schema supplied. Perhaps you meant http://h?
Error: No connection adapters were found for ':'
Error: Invalid URL '/': No schema supplied. Perhaps you meant http:///?
Upvotes: 0
Views: 124
Reputation: 42312
test_urls
is a string (not an array of strings), so you're iterating on each character and trying to GET h
, then t
, then t
, ...
And format
on the output of return_json
makes no sense. Nor does your print
(assuming you're using Python 3, print is a function).
Also requests has shortcuts for "Consider any status other than 2xx an error": Response.ok
and Response.raise_for_status()
.
And... why are you dump-ing the JSON response? If you want the textual version, just return Response.text
there's no reason to decode then immediately re-encode the response.
Upvotes: 1