0

I see you can parse usernames and passwords with:

from urlparse import urlparse
r = urlparse('http://myuser:mypass@example.com')
print r.username
# => 'myuser'

How can I go the other way? I can't use urlunparse because I can't do this:

r.username = request.args['username']
# => AttributeError: can't set attribute

I'm interested because the username contains characters that need escaped (namely: @, /).

Edit:

This string is coming from user input, so I won't know ahead of time what it is. It's a security risk to maintain your own list of escape characters, so string concatenation and custom character escaping with replace won't help here.

Joe
  • 16,328
  • 12
  • 61
  • 75
  • couldn't you do a simple `str.format(x,y,z)` before you set `r`? – taesu Sep 02 '15 at 22:51
  • @taesu No, the characters that need escaped won't get escaped that way. See my update. – Joe Sep 03 '15 at 03:08
  • @iAdjunct Writing your own copy of what needs escaped (and not maintaining it) is a security risk. – Joe Sep 03 '15 at 03:26

1 Answers1

2

Turns out the username part of basic auth URLs use the same escape characters that query parameters do.

So the answer is to use urllib.quote(username, safe='') then concatenate. (You'll need the safe parameter or / won't be escapted.)

Community
  • 1
  • 1
Joe
  • 16,328
  • 12
  • 61
  • 75