-1

I am making a post request and I have a payload variable but I am trying to set some of the data in the payload variable as user input so I am doing: payload = "{\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r}".format(name, pass)

I get this error:

File "testing.py", line 24, in sndReq
  payload = "{\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r}".format(name, pass)
KeyError: '\r"user"

If I take out .format and put hard values in there it works. (I also tried using an 'f' string)

My request line is this if it matters: r = requests.request("POST", url, data=payload, headers=headers)

dean0
  • 1
  • 1
    Don’t manually cobble together JSON as string. Make a dict and JSON-encode it: `json.dumps({'user': name, ...})`. Or you can probably pass the dict as is to requests. – deceze Jan 24 '21 at 08:29
  • The concrete reason for the error message is that the `{` in your format string have two different meanings. But again, this is the worst way to make JSON data to begin with anyway. – deceze Jan 24 '21 at 08:31
  • don't use `pass` as a variable name, it is a `reserved keyword` in python. – Epsi95 Jan 24 '21 at 08:31

1 Answers1

1

It seems your string is not formatted/escaped properly. How about doing something which is more readable, such as:

import requests

# some example values because your question doesn't give too many details
user, password ="user", "password"
url="http://google.com" # example url
headers={'pragma': 'no-cache'} # whatever your headers are

# now do the request, note we're not passing a single string here
requests.post(
    url, 
    json={
      "user": user, 
      "password": password
    }, 
    headers=headers
)

Additionally, I'd encourage you to work with something a bit easier than those unreadable strings! Put it into something that python (and us) can work with more easily. The first thing I'd do is get your string into a python object:

import json
payload = "{\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r}"
data=json.loads(payload)
data.update({'password': 'secret', 'user': 'me'})
# {u'password': 'secret', u'user': 'me', u'gdn': 0}

And finally, if you truly want to use the {} as the format string (which I hope the rest of my answer shows you is much more difficult than you need to make it), you'll need to remove the leading and trailing braces in the formatted text:

"{" + "\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r".format("user", "secret") + "}"
# '{\r"user": "user",\r"password": "secret",\r"gdn": 0\r}
David542
  • 104,438
  • 178
  • 489
  • 842