[英]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: 我不能使用
urlunparse
因为我不能这样做:
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. 维护您自己的转义字符列表会带来安全隐患,因此,字符串连接和使用
replace
自定义字符转义将无济于事。
Turns out the username part of basic auth URLs use the same escape characters that query parameters do. 事实证明,基本身份验证URL的用户名部分使用与查询参数相同的转义字符 。
So the answer is to use urllib.quote(username, safe='')
then concatenate. 因此答案是使用
urllib.quote(username, safe='')
然后进行连接。 ( You'll need the safe
parameter or /
won't be escapted.) ( 你需要的
safe
参数或/
不会escapted。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.