在用户认证和证书认证中,我该使用urllib、urllib2还是curl?

1 投票
1 回答
842 浏览
提问于 2025-04-16 05:49

几个月前,我匆忙写了一个Python程序,用来访问我公司的网络服务API。这个程序有三种不同的工作模式:

1) 不需要身份验证的HTTP
2) 需要用户名和密码的HTTP
3) 需要客户端证书的HTTPS

我成功地用urllib实现了第一种模式,但在第二和第三种模式上遇到了问题。我没有花时间去解决这些问题,而是计算了curl的正确命令行参数,然后通过os.system()来执行它。

现在我有机会重新写这个程序,利用我之前的经验,但我不确定是该继续使用urllib、urllib2,还是直接用curl。

urllib的文档提到:

When performing basic authentication, a FancyURLopener instance 
calls its prompt_user_passwd() method. The default implementation 
asks the users for the required     information on the controlling 
terminal. A subclass may override this method to support 
more appropriate behavior if needed.

它还提到了**x509参数给urllib.URLopener():

Additional keyword parameters, collected in x509, may be used for 
authentication of the client when using the https: scheme. The 
keywords key_file and cert_file are supported to provide an SSL 
key and certificate; both are needed to support client 
authentication.

不过,urllib2比urllib多了一些功能,所以我自然想用它。urllib2的文档里有很多关于身份验证处理的内容,似乎是为第二种模式设计的,但完全没有提到客户端证书。

我的问题是:我是否应该使用urllib,因为它似乎支持我需要的所有功能?还是说我应该继续使用curl?

谢谢。

编辑:也许我的问题不够具体,所以我再问一次。我能用urllib实现我想做的事情吗?或者用urllib2?还是说我必须出于必要性使用curl?

1 个回答

-1

我觉得你需要的模块是 mechanize

补充说明:mechanize 这个模块里的对象有一个用来认证的方法:add_password(self, url, user, password, realm=None)

撰写回答