#๐Ÿ”’ Keyerror in string

60 messages ยท Page 1 of 1 (latest)

cursive bobcat
#
  payload = "{\n  \"AuthToken\": \"" + auth.strip() + "\"\n}"
KeyError: '\n  "AuthToken"'

any reason python is throwing this to me?

sudden topazBOT
#

@cursive bobcat

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

gray meteor
#

also there seems to be more than just that

#

so send the whole traceback

#

!traceback

sudden topazBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

cursive bobcat
#

im working with this api which is really specific about how i send this request

#
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "/root/EsportsBot/cogs/ggleap.py", line 42, in get_jwt
    r = await (JWT()).renew(self.tk.strip())
  File "/root/EsportsBot/cogs/utils/ggLeap.py", line 10, in renew
    payload = "{\n  \"AuthToken\": \"" + auth.strip() + "\"\n}"
KeyError: '\n  "AuthToken"'
gray meteor
#
>>> payload = "{\n  \"AuthToken\": \"" + auth.strip() + "\"\n}"
>>>
``` doesnt error for me
cursive bobcat
gray meteor
#

really doesnt make sense

cursive bobcat
#

lemme try

#

uhhh

#
"""{
"AuthToken": "{0}"
}""".format(auth.strip())
#

holy shit ```
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "/root/EsportsBot/cogs/ggleap.py", line 42, in get_jwt
r = await (JWT()).renew(self.tk.strip())
File "/root/EsportsBot/cogs/utils/ggLeap.py", line 10, in renew
payload = """{
KeyError: '\n "AuthToken"'

#

this will work in another program when i straight up paste the value of auth into this string

placid pond
#

!xy
What are you trying to do? ๐Ÿ˜…

sudden topazBOT
#
xy-problem

The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.

Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.

For more information and examples, see http://xyproblem.info/.

cursive bobcat
#

ok so basically

#

let me know if you can't access that

#
async def renew(self, auth: str):
        payload = """{
                "AuthToken": "{0}"
                }""".format(auth.strip())
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{API_URL}/authorization/public-api/auth", data=payload, headers={'Content-Type': 'application/json-patch+json'}) as resp:
                print(resp.status)
                t = await resp.text()
                print(t)
                return resp.status, t
``` this is all of the code for the function
placid pond
cursive bobcat
#

(it's inside a discord bot)

#

I'm trying to make an api request to this api to obtain a JWT key, more specifically, trying to format the payload correctly so the API doesn't throw a HTTP 400

cursive bobcat
#

gotcha

placid pond
#

thats the weirdest format

gray meteor
#

does the \n really need to be there?

#

also maybe use single quotes to define the string to have to avoid the \

placid pond
#

so youโ€™ll get:
payload = """{ 'AuthToken': 'TOKEN' }"""??

cursive bobcat
gray meteor
gray meteor
cursive bobcat
#

no prob

placid pond
#

!e

payload = """{
    'AuthToken': 'TOKEN'
}"""
print(payload)
sudden topazBOT
#

@placid pond :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | {
002 |     'AuthToken': 'TOKEN'
003 | }
gray meteor
#
async def renew(self, auth: str):
        payload = """{
                "AuthToken": "{0}"
}""".format(auth.strip())
        async with aiohttp.ClientSession() as session:
            async with session.post(f"{API_URL}/authorization/public-api/auth", data=payload, headers={'Content-Type': 'application/json-patch+json'}) as resp:
                print(resp.status)
                t = await resp.text()
                print(t)
                return resp.status, t``` also u cant have the spaces like that for the payload
#

btw why not use f-strings?

#

yes i know this is off topic

#

but just a suggestion

cursive bobcat
#

i thought it wouldnt work with the other brackets lol Dentge

gray meteor
#

well true

#

u use double {

cursive bobcat
#

ohhh

#

that i didnt know

gray meteor
#

these seems like a very specific error

#

which i obviously cant try out cause the website is weird

cursive bobcat
#

Yeah im getting trolled ```
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "/root/EsportsBot/cogs/ggleap.py", line 42, in get_jwt
r = await (JWT()).renew(self.tk.strip())
File "/root/EsportsBot/cogs/utils/ggLeap.py", line 12, in renew
}""".format(auth.strip())
KeyError: '\n "AuthToken"'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/jishaku/features/invocation.py", line 165, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/usr/local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.10/site-packages/discord/ext/commands/core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '\n "AuthToken"'

#

i think the bottom error is irrelevant but i included it for transparency

cursive bobcat
#

Ok i fixed it

#

part of the issue is that when you reload a cog in discord.py it doesn't reload the modules attached

#

But this bit ended up working ```py
payload = f"{{\n "AuthToken": "{auth.strip()}"\n}}"

#

?solved

#

!solved

sudden topazBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.