我一直在尝试使用线程发出多个HTTP请求。
首先,我有一个调用API的方法,该方法将dict作为参数并返回一个JSON对象。此外,当我在没有线程的情况下运行它时,它工作得很好。但是,这是我尝试使用线程时遇到的代码和错误。
import sys
sys.path.append(r'C:/dict/path')
import apiModule
import threading
token = 'xxxx'
apiModule = apiModule.Module(token)
urls = [{'url': 'http://www.example.com'}, {'url': 'http://www.example.com/2'}]
data = []
for element in urls:
thread = threading.Thread(target=apiModule.method(),kwargs=element)
thread.start()
data.append(thread)
Traceback (most recent call last):
File "<pyshell#72>", line 2, in <module>
thread = threading.Thread(target=apiModule.method(),kwargs=element)
File "C:/dict/path", line 54, in method
return json.loads(r.content)
File "C:\Python27\lib\json\__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
任何帮助将不胜感激!
答案 0 :(得分:0)
扩展@fatetru的回复:根据threading documentation:
调用的可调用对象
target
是run()
方法
在您的示例中,您传递target=apiModule.method()
,立即在method
上调用“apiModule
”方法。这会引发您所看到的错误。目前,该代码甚至没有达到thread.start()
来电。