Repository navigation
not ascii characters in Cookies #3240
Replies: 2 comments 1 reply
|
You can try the following methods, which may solve your problem. |
|
Cookie values are not arbitrary Unicode header text. Changing the header encoding would not define how the server interprets a non-ASCII cookie value. If you control both ends, agree on an ASCII-safe value encoding, for example UTF-8 percent encoding: from urllib.parse import quote, unquote
import httpx
cookies = httpx.Cookies()
cookies.set("blablalba", quote("sprühkopf", safe=""), domain="example.com")
request = httpx.Request("GET", "https://example.com", cookies=cookies)
assert request.headers["cookie"] == "blablalba=spr%C3%BChkopf"
assert unquote(cookies.get("blablalba", domain="example.com")) == "sprühkopf"The percent decoding above is part of your application protocol; a server is not required to decode cookie values automatically. If the destination requires a particular existing cookie representation, follow its documented encoding instead. This does not make an opaque, server-issued session token interchangeable with a re-encoded token. Checked the outgoing ASCII Cookie header and the explicit round trip on HTTPX 0.28.1. This avoids private-header monkey patches but requires agreement with the receiving application. Cookies API. Validation: HTTPX 0.28.1, Python 3.11.9. |
Uh oh!
There was an error while loading. Please reload this page.
I need to pass a cookie with non-ascii characters to Client:
raise
UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 13: ordinal not in range(128)in Headers.setitem()Class Headers has a mechanism to switch to "iso-8859-1" encoding for situations like this, but it only works during a session. Class Request creates a new instance of Headers with "ascii" encoding by default, so there are no methods to set a different encoding other than Monkey Patching.
Maybe I'm wrong?
All reactions