Debian Codegraph @

python/curl/__init__.py

raw
1 '''A high-level interface to the pycurl extension'''
2
3 # ** mfx NOTE: the CGI class uses "black magic" using COOKIEFILE in
4 # combination with a non-existent file name. See the libcurl docs
5 # for more info.
6
7 import sys, pycurl
8 import urllib.parse as urllib_parse
9 from urllib.parse import urljoin
10 from io import BytesIO
11
12 # We should ignore SIGPIPE when using pycurl.NOSIGNAL - see
13 # the libcurl tutorial for more info.
14 try:
15 import signal
16 from signal import SIGPIPE, SIG_IGN
17 except ImportError:
18 pass
19 else:
20 signal.signal(SIGPIPE, SIG_IGN)
21
22
23 class Curl:
24 "High-level interface to pycurl functions."
25 def __init__(self, base_url="", fakeheaders=None):
26 self.handle = pycurl.Curl()
27 # These members might be set.
28 self.set_url(base_url)
29 self.verbosity = 0
30 self.fakeheaders = fakeheaders or []
31 # Nothing past here should be modified by the caller.
32 self.payload = None
33 self.payload_io = BytesIO()
34 self.hdr = ""
35 # Verify that we've got the right site; harmless on a non-SSL connect.
36 self.set_option(pycurl.SSL_VERIFYHOST, 2)
37 # Follow redirects in case it wants to take us to a CGI...
38 self.set_option(pycurl.FOLLOWLOCATION, 1)
39 self.set_option(pycurl.MAXREDIRS, 5)
40 self.set_option(pycurl.NOSIGNAL, 1)
41 # Setting this option with even a nonexistent file makes libcurl
42 # handle cookie capture and playback automatically.
43 self.set_option(pycurl.COOKIEFILE, "/dev/null")
44 # Set timeouts to avoid hanging too long
45 self.set_timeout(30)
46 # Use password identification from .netrc automatically
47 self.set_option(pycurl.NETRC, 1)
48 self.set_option(pycurl.WRITEFUNCTION, self.payload_io.write)
49 def header_callback(x):
50 self.hdr += x.decode('ascii')
51 self.set_option(pycurl.HEADERFUNCTION, header_callback)
52
53 def set_timeout(self, timeout):
54 "Set timeout for a retrieving an object"
55 self.set_option(pycurl.TIMEOUT, timeout)
56
57 def set_url(self, url):
58 "Set the base URL to be retrieved."
59 self.base_url = url
60 self.set_option(pycurl.URL, self.base_url)
61
62 def set_option(self, *args):
63 "Set an option on the retrieval."
64 self.handle.setopt(*args)
65
66 def set_verbosity(self, level):
67 "Set verbosity to 1 to see transactions."
68 self.set_option(pycurl.VERBOSE, level)
69
70 def __request(self, relative_url=None):
71 "Perform the pending request."
72 if self.fakeheaders:
73 self.set_option(pycurl.HTTPHEADER, self.fakeheaders)
74 if relative_url:
75 self.set_option(pycurl.URL, urljoin(self.base_url, relative_url))
76 self.payload = None
77 self.payload_io.seek(0)
78 self.payload_io.truncate()
79 self.hdr = ""
80 self.handle.perform()
81 self.payload = self.payload_io.getvalue()
82 return self.payload
83
84 def get(self, url="", params=None):
85 "Ship a GET request for a specified URL, capture the response."
86 if params:
87 url += "?" + urllib_parse.urlencode(params)
88 self.set_option(pycurl.HTTPGET, 1)
89 return self.__request(url)
90
91 def head(self, url="", params=None):
92 "Ship a HEAD request for a specified URL, capture the response."
93 if params:
94 url += "?" + urllib_parse.urlencode(params)
95 self.set_option(pycurl.NOBODY, 1)
96 return self.__request(url)
97
98 def post(self, cgi, params):
99 "Ship a POST request to a specified CGI, capture the response."
100 self.set_option(pycurl.POST, 1)
101 self.set_option(pycurl.POSTFIELDS, urllib_parse.urlencode(params))
102 return self.__request(cgi)
103
104 def body(self):
105 "Return the body from the last response."
106 return self.payload
107
108 def header(self):
109 "Return the header from the last response."
110 return self.hdr
111
112 def get_info(self, *args):
113 "Get information about retrieval."
114 return self.handle.getinfo(*args)
115
116 def info(self):
117 "Return a dictionary with all info on the last response."
118 m = {}
119 m['effective-url'] = self.handle.getinfo(pycurl.EFFECTIVE_URL)
120 m['http-code'] = self.handle.getinfo(pycurl.HTTP_CODE)
121 m['total-time'] = self.handle.getinfo(pycurl.TOTAL_TIME)
122 m['namelookup-time'] = self.handle.getinfo(pycurl.NAMELOOKUP_TIME)
123 m['connect-time'] = self.handle.getinfo(pycurl.CONNECT_TIME)
124 m['pretransfer-time'] = self.handle.getinfo(pycurl.PRETRANSFER_TIME)
125 m['redirect-time'] = self.handle.getinfo(pycurl.REDIRECT_TIME)
126 m['redirect-count'] = self.handle.getinfo(pycurl.REDIRECT_COUNT)
127 m['size-upload'] = self.handle.getinfo(pycurl.SIZE_UPLOAD)
128 m['size-download'] = self.handle.getinfo(pycurl.SIZE_DOWNLOAD)
129 m['speed-upload'] = self.handle.getinfo(pycurl.SPEED_UPLOAD)
130 m['header-size'] = self.handle.getinfo(pycurl.HEADER_SIZE)
131 m['request-size'] = self.handle.getinfo(pycurl.REQUEST_SIZE)
132 m['content-length-download'] = self.handle.getinfo(pycurl.CONTENT_LENGTH_DOWNLOAD)
133 m['content-length-upload'] = self.handle.getinfo(pycurl.CONTENT_LENGTH_UPLOAD)
134 m['content-type'] = self.handle.getinfo(pycurl.CONTENT_TYPE)
135 m['response-code'] = self.handle.getinfo(pycurl.RESPONSE_CODE)
136 m['speed-download'] = self.handle.getinfo(pycurl.SPEED_DOWNLOAD)
137 m['ssl-verifyresult'] = self.handle.getinfo(pycurl.SSL_VERIFYRESULT)
138 m['filetime'] = self.handle.getinfo(pycurl.INFO_FILETIME)
139 m['starttransfer-time'] = self.handle.getinfo(pycurl.STARTTRANSFER_TIME)
140 m['redirect-time'] = self.handle.getinfo(pycurl.REDIRECT_TIME)
141 m['redirect-count'] = self.handle.getinfo(pycurl.REDIRECT_COUNT)
142 m['http-connectcode'] = self.handle.getinfo(pycurl.HTTP_CONNECTCODE)
143 m['httpauth-avail'] = self.handle.getinfo(pycurl.HTTPAUTH_AVAIL)
144 m['proxyauth-avail'] = self.handle.getinfo(pycurl.PROXYAUTH_AVAIL)
145 m['os-errno'] = self.handle.getinfo(pycurl.OS_ERRNO)
146 m['num-connects'] = self.handle.getinfo(pycurl.NUM_CONNECTS)
147 m['ssl-engines'] = self.handle.getinfo(pycurl.SSL_ENGINES)
148 m['cookielist'] = self.handle.getinfo(pycurl.INFO_COOKIELIST)
149 m['lastsocket'] = self.handle.getinfo(pycurl.LASTSOCKET)
150 m['ftp-entry-path'] = self.handle.getinfo(pycurl.FTP_ENTRY_PATH)
151 return m
152
153 def answered(self, check):
154 "Did a given check string occur in the last payload?"
155 return self.payload.find(check) >= 0
156
157 def close(self):
158 "Close a session, freeing resources."
159 if self.handle:
160 self.handle.close()
161 self.handle = None
162 self.hdr = ""
163 self.payload = ""
164
165 def __del__(self):
166 self.close()
167
168
169 if __name__ == "__main__":
170 if len(sys.argv) < 2:
171 url = 'https://curl.haxx.se'
172 else:
173 url = sys.argv[1]
174 c = Curl()
175 c.get(url)
176 print(c.body())
177 print('='*74 + '\n')
178 import pprint
179 pprint.pprint(c.info())
180 print(c.get_info(pycurl.OS_ERRNO))
181 print(c.info()['os-errno'])
182 c.close()