Skip to main content
 首页 » 编程设计

python之urllib2 是否支持线程到需要基本身份验证的服务器

2025年05月04日9luoye11

我正在开发一个应用程序,它使用一系列 REST 调用来检索数据。我已经完成了基本的应用逻辑,数据检索的结构大致如下。

1)初始数据调用完成

2) 对于初始调用中的每个响应,都会对需要基本身份验证的其余服务执行后续数据调用。

按顺序执行这些调用可能会增加最终用户的等待时间,因此我正在尝试实现线程以加快进程(受 IO 限制使它成为线程的理想候选者)。问题是我在线程调用的身份验证方面遇到了问题。

如果我按顺序执行调用,那么一切正常,但如果我使用线程方法设置它,我最终会遇到 401 身份验证错误或来自服务器的 500 内部服务器错误。

我已经与 REST 服务管理员谈过,他们不知道什么会阻止服务器端同一用户的并发连接,所以我想知道这是否是 urllib2 端的问题。

有没有人有这方面的经验?

编辑:

虽然我无法发布确切的代码,但我会发布我正在使用非常相似的结构所做的合理表示。

import threading 
class UrlThread(threading.Thread): 
    def __init__(self, data): 
        threading.Thread.__init__(self) 
        self.data = data 
 
    def run(self): 
        password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() 
        password_manager.add_password(None, 'https://url/to/Rest_Svc/', 'uid', 'passwd') 
        auth_manager = urllib2.HTTPBasicAuthHandler(password_manager) 
        opener = urllib2.build_opener(auth_manager) 
        urllib2.install_opener(opener) 
        option = data[0] 
        urlToOpen = 'https://url/to/Rest_Svc/?option='+option 
        rawData = urllib2.urlopen(urlToOpen) 
        wsData = rawData.readlines() 
        if wsData: 
            print('success') 
 
#firstCallRows is a list of lists containing the data returned  
#from the initial call I mentioned earlier. 
thread_list = [] 
for row in firstCallRows: 
    t = UrlThread(row) 
    t.setDaemon(True) 
    t.start() 
    thread_list.append(t) 
 
for thread in thread_list: 
    thread.join() 

请您参考如下方法:

与 Requests你可以这样做:

from requests import session, async 
 
auth = ('username', 'password') 
url = 'http://example.com/api/' 
options = ['foo1', 'foo2', 'foo3'] 
 
s = session(auth=auth) 
 
rs = [async.get(url, params={'option': opt}, session=s) for opt in options] 
 
responses = async.imap(rs) 
 
for r in responses: 
    print r.text 

相关文档:
Sessions
Asynchronous requests
Basic authentication