Python: requests module throws exception with Geve

2019-04-08 21:25发布

问题:

The following code:

import gevent
import gevent.monkey
gevent.monkey.patch_socket()

import requests
import json

base_url = 'https://api.getclever.com'
section_url = base_url + '/v1.1/sections'

#get all sections
sections = requests.get(section_url, auth=('DEMO_KEY', '')).json()
urls = [base_url+data['uri']+'/students' for data in sections['data']]

#get students for each section
threads = [gevent.spawn(requests.get, url, auth=('DEMO_KEY', '')) for url in urls]
gevent.joinall(threads)
students = [thread.value for thread in threads]

#get number of students in each section
num_students = [len(student.json()['data']) for student in students]
print (sum(num_students)/len(num_students))

results in this error:

Traceback (most recent call last):
  File "clever.py", line 12, in <module>
    sections = requests.get(section_url, auth=('DEMO_KEY', '')).json()
  File "/Library/Python/2.7/site-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 382, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 485, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 379, in send
    raise SSLError(e)
requests.exceptions.SSLError: [Errno 2] _ssl.c:503: The operation did not complete (read)

What am I doing wrong here?

回答1:

Here's a similar question: [Errno 2] _ssl.c:504: The operation did not complete (read).

When you comment out

gevent.monkey.patch_socket()

or use

gevent.monkey.patch_all()

or use

gevent.monkey.patch_socket()
gevent.monkey.patch_ssl()

then the problem disappears.