httpcon用于生成HTTP中的连接。 Attributes: timeout: 超时时间
| 40 | |
| 41 | |
| 42 | class httpcon(object): |
| 43 | ''' |
| 44 | httpcon用于生成HTTP中的连接。 |
| 45 | |
| 46 | Attributes: |
| 47 | timeout: 超时时间 |
| 48 | ''' |
| 49 | |
| 50 | def __init__(self, timeout=10): |
| 51 | self.timeout = timeout |
| 52 | self.protocol = [] |
| 53 | self._get_protocol() |
| 54 | |
| 55 | def _get_protocol(self): |
| 56 | if not self.protocol: |
| 57 | ps = ( |
| 58 | 'PROTOCOL_SSLv23', 'PROTOCOL_TLSv1', |
| 59 | 'PROTOCOL_SSLv2', 'PROTOCOL_TLSv1_1', 'PROTOCOL_TLSv1_2') |
| 60 | for p in ps: |
| 61 | pa = getattr(ssl, p, None) |
| 62 | if pa: |
| 63 | self.protocol.append(pa) |
| 64 | |
| 65 | ''' |
| 66 | 得到一个连接 |
| 67 | |
| 68 | 这是连接池中最重要的一个参数,连接生成、复用相关操作都在这 |
| 69 | ''' |
| 70 | |
| 71 | def get_con(self, url, proxy=None): |
| 72 | scheme, host, port, path = url |
| 73 | conn = self._make_con(scheme, host, port, proxy) |
| 74 | return conn |
| 75 | |
| 76 | def _make_con(self, scheme, host, port, proxy=None): |
| 77 | if "https" != scheme: |
| 78 | if proxy: |
| 79 | con = client.HTTPConnection( |
| 80 | proxy[0], int(proxy[1]), timeout=self.timeout) |
| 81 | con.set_tunnel(host, port) |
| 82 | else: |
| 83 | con = client.HTTPConnection(host, port, timeout=self.timeout) |
| 84 | # con.connect() |
| 85 | return con |
| 86 | for p in self.protocol: |
| 87 | context = ssl._create_unverified_context(p) |
| 88 | try: |
| 89 | if proxy: |
| 90 | con = client.HTTPSConnection( |
| 91 | proxy[0], proxy[1], context=context, |
| 92 | timeout=self.timeout) |
| 93 | con.set_tunnel(host, port) |
| 94 | else: |
| 95 | con = client.HTTPSConnection( |
| 96 | host, port, context=context, timeout=self.timeout) |
| 97 | # con.connect() |
| 98 | return con |
| 99 | except ssl.SSLError: |