| 1 |
# Exposing rich exception information from callbacks example |
| 2 |
|
| 3 |
import pycurl, random, socket |
| 4 |
|
| 5 |
class ConnectionRejected(Exception): |
| 6 |
pass |
| 7 |
|
| 8 |
def opensocket(curl, purpose, curl_address): |
| 9 |
if random.random() < 0.5: |
| 10 |
curl.exception = ConnectionRejected('Rejecting connection attempt in opensocket callback') |
| 11 |
return pycurl.SOCKET_BAD |
| 12 |
|
| 13 |
family, socktype, protocol, address = curl_address |
| 14 |
s = socket.socket(family, socktype, protocol) |
| 15 |
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) |
| 16 |
return s |
| 17 |
|
| 18 |
c = pycurl.Curl() |
| 19 |
c.setopt(c.URL, 'http://pycurl.io') |
| 20 |
c.exception = None |
| 21 |
c.setopt(c.OPENSOCKETFUNCTION, |
| 22 |
lambda purpose, address: opensocket(c, purpose, address)) |
| 23 |
|
| 24 |
try: |
| 25 |
c.perform() |
| 26 |
except pycurl.error as e: |
| 27 |
if e.args[0] == pycurl.E_COULDNT_CONNECT and c.exception: |
| 28 |
print(c.exception) |
| 29 |
else: |
| 30 |
print(e) |