简体   繁体   中英

How do you build a URL that contains a username and password from user input in Python?

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM