【发布时间】:2018-08-22 02:22:45
【问题描述】:
我在 python 2.6
HTTPD 2.2.15
CentOS 6
我正在编写一个涉及进行大量 REST API 调用的 Python 脚本。我决定尝试通过多线程处理 URL 请求来提高程序的速度。我使用了请求模块,一切正常。我不得不切换到 pycurl,所以我复制了我可以使用的 pycurl 代码。
现在,当我运行代码时,有时会在某些线程中出错。每次都不是相同的线程。通过注释掉除 1 之外的所有线程,我无法重现该错误,但只需要 2 个或更多线程,错误就会出现。
我无法分享确切的代码,但这是一个近似值:
import os
import datetime
import time
import pycurl
import threading
from StringIO import StringIO
from pprint import pprint as pprint
import json
variable1 = {}
variable2 = {"x": {}, "y": {}}
def pycurl_method(url, creds):
buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.USERPWD, creds[0] + ':' + creds[1])
c.setopt(c.WRITEFUNCTION, buffer.write)
c.perform()
c.close()
response = buffer.getvalue()
return json.loads(response)
def url_method(url, creds):
env = threading.current_thread().getName()
response = pycurl_method(url, creds)
...Do stuff...
def start_threads(threads):
for thread in threads:
thread.start()
def join_threads(threads):
for thread in threads:
thread.join()
def main():
apiUrl0 = "some URL"
apiUrl1 = "some different URL"
apiUrl2 = "etc"
...
creds = #returns credentials from a file stored on the server as [username,password]
#Multithread API calls
t0 = threading.Thread(target=url_method, name='nameOfThread0', args=(apiUrl0, creds))
t1 = threading.Thread(target=url_method, name='nameOfThread1', args=(apiUrl1, creds))
t2 = threading.Thread(target=url_method, name='nameOfThread2', args=(apiUrl2, creds))
...
start_threads([t0, t1, t2, ...etc...])
join_threads([t0, t1, t2, ...etc...])
错误是这样的:
文件“this_script.py”,行 xyz,在 url_method
c.perform()
错误:(77,'SSL CA 证书问题(路径?访问权限?)')
如果我删除线程并按顺序执行,我不会收到任何错误。
我认为这可能与 pycurl 有关(因为 requests 很好)。
具体来说,pycurl.Curl().
我想知道每个线程是否以某种方式使用相同的 pycurl.Curl() 并踩到其他线程的脚趾。
为什么会出现这些错误?
我怎样才能避免它们?
threading 和 pycurl 模块不能很好地配合使用吗?
【问题讨论】:
标签: linux apache python-multithreading python-2.6 pycurl