Saha
Saha

Reputation: 89

Python string substitution picking up junk characters in api requests

I am using Pagerduty python api client - pdpyras And below is the block of code

session = APISession(api_token)
changedate = os.popen("date -u -d '24 hours ago' +'%FT%T%.2Z'").read()
print(changedate)
changeurl = "change_events?include[]=integration&since=" + changedate
print(changeurl)
change_dump = session.rget(changeurl)
print(change_dump[0])

This should ideally get me the 1st event from change-events page of pagerduty. However, it fails due to the junk characters that gets added in the changeurl when it is passed to session.rget

See the below output

2021-03-26T09:47:53.2Z

change_events?include[]=integration&since=2021-03-26T09:47:53.2Z

Traceback (most recent call last):
  File "dailyincidents.py", line 28, in <module>
    change_dump = session.rget(changeurl)
  File "/Users/saha/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pdpyras.py", line 190, in call
    return method(self, url, **kw)
  File "/Users/saha/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pdpyras.py", line 143, in call
    r = raise_on_error(method(self, path, **pass_kw))
  File "/Users/saha/.pyenv/versions/3.7.7/lib/python3.7/site-packages/pdpyras.py", line 84, in raise_on_error
    ), response=r
pdpyras.PDClientError: GET /change_events?include%5B%5D=integration&since=2021-03-26T09:47:53.2Z%0A: API responded with non-success status (400)

The problem here is the junk characters you see in the last line of error "include%5B%5D" and then "%0A" in the end. Because if I run the below code block directly, I am able to successfully pull the details.

change_dump = session.rget("change_events?include[]=integration&since=2021-03-26T09:47:53.2Z")

The issue occurs only when the string gets substituted, it takes these junk characters. Not sure how it gets picked and how to get around this. Any pointers?

EDIT

I was able to partly get rid of the junk characters. However, there is still one at the end, which I am not sure how to. Below is the change I did.

parameters = "include[]=integration&since=" + changedate
change_dump = session.rget("change_events", params=parameters)

Now, the error is like below

pdpyras.PDClientError: GET /change_events?include[]=integration&since=2021-03-26T14:14:08.2Z%0A: API responded with non-success status (400)

As you can see, now the last 3 characters in the url which is %0A: is causing the problem. Any pointers please?

Upvotes: 1

Views: 208

Answers (1)

Gokul
Gokul

Reputation: 191

The below format should work for you.

parameters = "include[]=integration&since=" + changedate
change_dump = session.rget("change_events",params=parameters.rstrip('\n').replace("\n", ""))

Upvotes: 1

Related Questions