| 1 |
PycURL Quick Start |
| 2 |
================== |
| 3 |
|
| 4 |
Retrieving A Network Resource |
| 5 |
----------------------------- |
| 6 |
|
| 7 |
Once PycURL is installed we can perform network operations. The simplest |
| 8 |
one is retrieving a resource by its URL. To issue a network request with |
| 9 |
PycURL, the following steps are required: |
| 10 |
|
| 11 |
1. Create a ``pycurl.Curl`` instance. |
| 12 |
2. Use ``setopt`` to set options. |
| 13 |
3. Call ``perform`` to perform the operation. |
| 14 |
|
| 15 |
Here is how we can retrieve a network resource:: |
| 16 |
|
| 17 |
import pycurl |
| 18 |
import certifi |
| 19 |
from io import BytesIO |
| 20 |
|
| 21 |
buffer = BytesIO() |
| 22 |
c = pycurl.Curl() |
| 23 |
c.setopt(c.URL, 'http://pycurl.io/') |
| 24 |
c.setopt(c.WRITEDATA, buffer) |
| 25 |
c.setopt(c.CAINFO, certifi.where()) |
| 26 |
c.perform() |
| 27 |
c.close() |
| 28 |
|
| 29 |
body = buffer.getvalue() |
| 30 |
# Body is a byte string. |
| 31 |
# We have to know the encoding in order to print it to a text file |
| 32 |
# such as standard output. |
| 33 |
print(body.decode('iso-8859-1')) |
| 34 |
|
| 35 |
This code is available as ``examples/quickstart/get.py``. |
| 36 |
|
| 37 |
PycURL does not provide storage for the network response - that is the |
| 38 |
application's job. Therefore we must setup a buffer (in the form of a |
| 39 |
BytesIO object) and instruct PycURL to write to that buffer. |
| 40 |
|
| 41 |
Most of the existing PycURL code uses WRITEFUNCTION instead of WRITEDATA |
| 42 |
as follows:: |
| 43 |
|
| 44 |
c.setopt(c.WRITEFUNCTION, buffer.write) |
| 45 |
|
| 46 |
While the WRITEFUNCTION idiom continues to work, it is now unnecessary. |
| 47 |
As of PycURL 7.19.3 WRITEDATA accepts any Python object with a ``write`` |
| 48 |
method. |
| 49 |
|
| 50 |
Working With HTTPS |
| 51 |
------------------ |
| 52 |
|
| 53 |
Most web sites today use HTTPS which is HTTP over TLS/SSL. In order to |
| 54 |
take advantage of security that HTTPS provides, PycURL needs to utilize |
| 55 |
a *certificate bundle*. As certificates change over time PycURL does not |
| 56 |
provide such a bundle; one may be supplied by your operating system, but |
| 57 |
if not, consider using the `certifi`_ Python package:: |
| 58 |
|
| 59 |
import pycurl |
| 60 |
import certifi |
| 61 |
from io import BytesIO |
| 62 |
|
| 63 |
buffer = BytesIO() |
| 64 |
c = pycurl.Curl() |
| 65 |
c.setopt(c.URL, 'https://python.org/') |
| 66 |
c.setopt(c.WRITEDATA, buffer) |
| 67 |
c.setopt(c.CAINFO, certifi.where()) |
| 68 |
# you can set proxy cainfo/capath to validate https the proxy |
| 69 |
# if you use one |
| 70 |
# c.setopt(c.PROXY, <your-proxy>) |
| 71 |
# c.setopt(c.PROXY_CAINFO, certifi.where()) |
| 72 |
c.perform() |
| 73 |
c.close() |
| 74 |
|
| 75 |
body = buffer.getvalue() |
| 76 |
# Body is a byte string. |
| 77 |
# We have to know the encoding in order to print it to a text file |
| 78 |
# such as standard output. |
| 79 |
print(body.decode('iso-8859-1')) |
| 80 |
|
| 81 |
This code is available as ``examples/quickstart/get.py`` (with HTTPS and certifi). |
| 82 |
|
| 83 |
|
| 84 |
Troubleshooting |
| 85 |
--------------- |
| 86 |
|
| 87 |
When things don't work as expected, use libcurl's ``VERBOSE`` option to |
| 88 |
receive lots of debugging output pertaining to the request:: |
| 89 |
|
| 90 |
c.setopt(c.VERBOSE, True) |
| 91 |
|
| 92 |
It is often helpful to compare verbose output from the program using PycURL |
| 93 |
with that of ``curl`` command line tool when the latter is invoked with |
| 94 |
``-v`` option:: |
| 95 |
|
| 96 |
curl -v http://pycurl.io/ |
| 97 |
|
| 98 |
|
| 99 |
Examining Response Headers |
| 100 |
-------------------------- |
| 101 |
|
| 102 |
In reality we want to decode the response using the encoding specified by |
| 103 |
the server rather than assuming an encoding. To do this we need to |
| 104 |
examine the response headers:: |
| 105 |
|
| 106 |
import pycurl |
| 107 |
import re |
| 108 |
from io import BytesIO |
| 109 |
|
| 110 |
headers = {} |
| 111 |
def header_function(header_line): |
| 112 |
# HTTP standard specifies that headers are encoded in iso-8859-1. |
| 113 |
header_line = header_line.decode('iso-8859-1') |
| 114 |
|
| 115 |
# Header lines include the first status line (HTTP/1.x ...). |
| 116 |
# We are going to ignore all lines that don't have a colon in them. |
| 117 |
# This will botch headers that are split on multiple lines... |
| 118 |
if ':' not in header_line: |
| 119 |
return |
| 120 |
|
| 121 |
# Break the header line into header name and value. |
| 122 |
name, value = header_line.split(':', 1) |
| 123 |
|
| 124 |
# Remove whitespace that may be present. |
| 125 |
# Header lines include the trailing newline, and there may be whitespace |
| 126 |
# around the colon. |
| 127 |
name = name.strip() |
| 128 |
value = value.strip() |
| 129 |
|
| 130 |
# Header names are case insensitive. |
| 131 |
# Lowercase name here. |
| 132 |
name = name.lower() |
| 133 |
|
| 134 |
# Now we can actually record the header name and value. |
| 135 |
# Note: this only works when headers are not duplicated, see below. |
| 136 |
headers[name] = value |
| 137 |
|
| 138 |
buffer = BytesIO() |
| 139 |
c = pycurl.Curl() |
| 140 |
c.setopt(c.URL, 'http://pycurl.io') |
| 141 |
c.setopt(c.WRITEFUNCTION, buffer.write) |
| 142 |
# Set our header function. |
| 143 |
c.setopt(c.HEADERFUNCTION, header_function) |
| 144 |
c.perform() |
| 145 |
c.close() |
| 146 |
|
| 147 |
# Figure out what encoding was sent with the response, if any. |
| 148 |
# Check against lowercased header name. |
| 149 |
encoding = None |
| 150 |
if 'content-type' in headers: |
| 151 |
content_type = headers['content-type'].lower() |
| 152 |
match = re.search('charset=(\S+)', content_type) |
| 153 |
if match: |
| 154 |
encoding = match.group(1) |
| 155 |
print('Decoding using %s' % encoding) |
| 156 |
if encoding is None: |
| 157 |
# Default encoding for HTML is iso-8859-1. |
| 158 |
# Other content types may have different default encoding, |
| 159 |
# or in case of binary data, may have no encoding at all. |
| 160 |
encoding = 'iso-8859-1' |
| 161 |
print('Assuming encoding is %s' % encoding) |
| 162 |
|
| 163 |
body = buffer.getvalue() |
| 164 |
# Decode using the encoding we figured out. |
| 165 |
print(body.decode(encoding)) |
| 166 |
|
| 167 |
This code is available as ``examples/quickstart/response_headers.py``. |
| 168 |
|
| 169 |
That was a lot of code for something very straightforward. Unfortunately, |
| 170 |
as libcurl refrains from allocating memory for response data, it is on our |
| 171 |
application to perform this grunt work. |
| 172 |
|
| 173 |
One caveat with the above code is that if there are multiple headers |
| 174 |
for the same name, such as Set-Cookie, only the last header value will be |
| 175 |
stored. To record all values in multi-valued headers as a list the following |
| 176 |
code can be used instead of ``headers[name] = value`` line:: |
| 177 |
|
| 178 |
if name in headers: |
| 179 |
if isinstance(headers[name], list): |
| 180 |
headers[name].append(value) |
| 181 |
else: |
| 182 |
headers[name] = [headers[name], value] |
| 183 |
else: |
| 184 |
headers[name] = value |
| 185 |
|
| 186 |
|
| 187 |
Writing To A File |
| 188 |
----------------- |
| 189 |
|
| 190 |
Suppose we want to save response body to a file. This is actually easy |
| 191 |
for a change:: |
| 192 |
|
| 193 |
import pycurl |
| 194 |
|
| 195 |
# As long as the file is opened in binary mode, response body |
| 196 |
# can be written to it without decoding. |
| 197 |
with open('out.html', 'wb') as f: |
| 198 |
c = pycurl.Curl() |
| 199 |
c.setopt(c.URL, 'http://pycurl.io/') |
| 200 |
c.setopt(c.WRITEDATA, f) |
| 201 |
c.perform() |
| 202 |
c.close() |
| 203 |
|
| 204 |
This code is available as ``examples/quickstart/write_file.py``. |
| 205 |
|
| 206 |
The important part is opening the file in binary mode - then response body |
| 207 |
can be written bytewise without decoding or encoding steps. |
| 208 |
|
| 209 |
|
| 210 |
Following Redirects |
| 211 |
------------------- |
| 212 |
|
| 213 |
By default libcurl, and PycURL, do not follow redirects. Changing this |
| 214 |
behavior involves using ``setopt`` like so:: |
| 215 |
|
| 216 |
import pycurl |
| 217 |
|
| 218 |
c = pycurl.Curl() |
| 219 |
# Redirects to https://www.python.org/. |
| 220 |
c.setopt(c.URL, 'http://www.python.org/') |
| 221 |
# Follow redirect. |
| 222 |
c.setopt(c.FOLLOWLOCATION, True) |
| 223 |
c.perform() |
| 224 |
c.close() |
| 225 |
|
| 226 |
This code is available as ``examples/quickstart/follow_redirect.py``. |
| 227 |
|
| 228 |
As we did not set a write callback, the default libcurl and PycURL behavior |
| 229 |
to write response body to standard output takes effect. |
| 230 |
|
| 231 |
|
| 232 |
Setting Options |
| 233 |
--------------- |
| 234 |
|
| 235 |
Following redirects is one option that libcurl provides. There are many more |
| 236 |
such options, and they are documented on `curl_easy_setopt`_ page. |
| 237 |
With very few exceptions, PycURL option names are derived from libcurl |
| 238 |
option names by removing the ``CURLOPT_`` prefix. Thus, ``CURLOPT_URL`` |
| 239 |
becomes simply ``URL``. |
| 240 |
|
| 241 |
.. _curl_easy_setopt: https://curl.haxx.se/libcurl/c/curl_easy_setopt.html |
| 242 |
|
| 243 |
|
| 244 |
Examining Response |
| 245 |
------------------ |
| 246 |
|
| 247 |
We already covered examining response headers. Other response information is |
| 248 |
accessible via ``getinfo`` call as follows:: |
| 249 |
|
| 250 |
import pycurl |
| 251 |
from io import BytesIO |
| 252 |
|
| 253 |
buffer = BytesIO() |
| 254 |
c = pycurl.Curl() |
| 255 |
c.setopt(c.URL, 'http://pycurl.io/') |
| 256 |
c.setopt(c.WRITEDATA, buffer) |
| 257 |
c.perform() |
| 258 |
|
| 259 |
# HTTP response code, e.g. 200. |
| 260 |
print('Status: %d' % c.getinfo(c.RESPONSE_CODE)) |
| 261 |
# Elapsed time for the transfer. |
| 262 |
print('Time: %f' % c.getinfo(c.TOTAL_TIME)) |
| 263 |
|
| 264 |
# getinfo must be called before close. |
| 265 |
c.close() |
| 266 |
|
| 267 |
This code is available as ``examples/quickstart/response_info.py``. |
| 268 |
|
| 269 |
Here we write the body to a buffer to avoid printing uninteresting output |
| 270 |
to standard out. |
| 271 |
|
| 272 |
Response information that libcurl exposes is documented on |
| 273 |
`curl_easy_getinfo`_ page. With very few exceptions, PycURL constants |
| 274 |
are derived from libcurl constants by removing the ``CURLINFO_`` prefix. |
| 275 |
Thus, ``CURLINFO_RESPONSE_CODE`` becomes simply ``RESPONSE_CODE``. |
| 276 |
|
| 277 |
.. _curl_easy_getinfo: https://curl.haxx.se/libcurl/c/curl_easy_getinfo.html |
| 278 |
|
| 279 |
|
| 280 |
Sending Form Data |
| 281 |
----------------- |
| 282 |
|
| 283 |
To send form data, use ``POSTFIELDS`` option. Form data must be URL-encoded |
| 284 |
beforehand:: |
| 285 |
|
| 286 |
import pycurl |
| 287 |
from urllib.parse import urlencode |
| 288 |
|
| 289 |
c = pycurl.Curl() |
| 290 |
c.setopt(c.URL, 'https://httpbin.org/post') |
| 291 |
|
| 292 |
post_data = {'field': 'value'} |
| 293 |
# Form data must be provided already urlencoded. |
| 294 |
postfields = urlencode(post_data) |
| 295 |
# Sets request method to POST, |
| 296 |
# Content-Type header to application/x-www-form-urlencoded |
| 297 |
# and data to send in request body. |
| 298 |
c.setopt(c.POSTFIELDS, postfields) |
| 299 |
|
| 300 |
c.perform() |
| 301 |
c.close() |
| 302 |
|
| 303 |
This code is available as ``examples/quickstart/form_post.py``. |
| 304 |
|
| 305 |
``POSTFIELDS`` automatically sets HTTP request method to POST. Other request |
| 306 |
methods can be specified via ``CUSTOMREQUEST`` option:: |
| 307 |
|
| 308 |
c.setopt(c.CUSTOMREQUEST, 'PATCH') |
| 309 |
|
| 310 |
|
| 311 |
Building Multipart Trees With CurlMime (Draft) |
| 312 |
------------------------------------------ |
| 313 |
|
| 314 |
``CurlMime`` is a new object API for constructing multipart trees in a more |
| 315 |
Pythonic way than legacy ``HTTPPOST`` tuples. |
| 316 |
|
| 317 |
Example:: |
| 318 |
|
| 319 |
import pycurl |
| 320 |
|
| 321 |
curl = pycurl.Curl() |
| 322 |
mime = pycurl.CurlMime(curl) |
| 323 |
|
| 324 |
mime.add_field("title", "example") |
| 325 |
mime.add_file("upload", "/tmp/example.txt", content_type="text/plain") |
| 326 |
|
| 327 |
nested = mime.add_multipart(name="attachments", subtype="mixed") |
| 328 |
nested.add_field("meta", "nested-value") |
| 329 |
|
| 330 |
See :ref:`mime` for full API details. |
| 331 |
|
| 332 |
.. note:: |
| 333 |
|
| 334 |
This quick start section documents MIME tree construction. Full request |
| 335 |
attachment examples are being documented as MIME option integration is |
| 336 |
finalized. |
| 337 |
|
| 338 |
|
| 339 |
File Upload - Multipart POST |
| 340 |
---------------------------- |
| 341 |
|
| 342 |
To replicate the behavior of file upload in an HTML form (specifically, |
| 343 |
a multipart form), |
| 344 |
use ``HTTPPOST`` option. Such an upload is performed with a ``POST`` request. |
| 345 |
See the next example for how to upload a file with a ``PUT`` request. |
| 346 |
|
| 347 |
If the data to be uploaded is located in a physical file, |
| 348 |
use ``FORM_FILE``:: |
| 349 |
|
| 350 |
import pycurl |
| 351 |
|
| 352 |
c = pycurl.Curl() |
| 353 |
c.setopt(c.URL, 'https://httpbin.org/post') |
| 354 |
|
| 355 |
c.setopt(c.HTTPPOST, [ |
| 356 |
('fileupload', ( |
| 357 |
# upload the contents of this file |
| 358 |
c.FORM_FILE, __file__, |
| 359 |
)), |
| 360 |
]) |
| 361 |
|
| 362 |
c.perform() |
| 363 |
c.close() |
| 364 |
|
| 365 |
This code is available as ``examples/quickstart/file_upload_real.py``. |
| 366 |
|
| 367 |
``libcurl`` provides a number of options to tweak file uploads and multipart |
| 368 |
form submissions in general. These are documented on `curl_formadd page`_. |
| 369 |
For example, to set a different filename and content type:: |
| 370 |
|
| 371 |
import pycurl |
| 372 |
|
| 373 |
c = pycurl.Curl() |
| 374 |
c.setopt(c.URL, 'https://httpbin.org/post') |
| 375 |
|
| 376 |
c.setopt(c.HTTPPOST, [ |
| 377 |
('fileupload', ( |
| 378 |
# upload the contents of this file |
| 379 |
c.FORM_FILE, __file__, |
| 380 |
# specify a different file name for the upload |
| 381 |
c.FORM_FILENAME, 'helloworld.py', |
| 382 |
# specify a different content type |
| 383 |
c.FORM_CONTENTTYPE, 'application/x-python', |
| 384 |
)), |
| 385 |
]) |
| 386 |
|
| 387 |
c.perform() |
| 388 |
c.close() |
| 389 |
|
| 390 |
This code is available as ``examples/quickstart/file_upload_real_fancy.py``. |
| 391 |
|
| 392 |
If the file data is in memory, use ``BUFFER``/``BUFFERPTR`` as follows:: |
| 393 |
|
| 394 |
import pycurl |
| 395 |
|
| 396 |
c = pycurl.Curl() |
| 397 |
c.setopt(c.URL, 'https://httpbin.org/post') |
| 398 |
|
| 399 |
c.setopt(c.HTTPPOST, [ |
| 400 |
('fileupload', ( |
| 401 |
c.FORM_BUFFER, 'readme.txt', |
| 402 |
c.FORM_BUFFERPTR, 'This is a fancy readme file', |
| 403 |
)), |
| 404 |
]) |
| 405 |
|
| 406 |
c.perform() |
| 407 |
c.close() |
| 408 |
|
| 409 |
This code is available as ``examples/quickstart/file_upload_buffer.py``. |
| 410 |
|
| 411 |
|
| 412 |
File Upload - PUT |
| 413 |
----------------- |
| 414 |
|
| 415 |
A file can also be uploaded in request body, via a ``PUT`` request. |
| 416 |
Here is how this can be arranged with a physical file:: |
| 417 |
|
| 418 |
import pycurl |
| 419 |
|
| 420 |
c = pycurl.Curl() |
| 421 |
c.setopt(c.URL, 'https://httpbin.org/put') |
| 422 |
|
| 423 |
c.setopt(c.UPLOAD, 1) |
| 424 |
file = open('body.json') |
| 425 |
c.setopt(c.READDATA, file) |
| 426 |
|
| 427 |
c.perform() |
| 428 |
c.close() |
| 429 |
# File must be kept open while Curl object is using it |
| 430 |
file.close() |
| 431 |
|
| 432 |
This code is available as ``examples/quickstart/put_file.py``. |
| 433 |
|
| 434 |
And if the data is stored in a buffer:: |
| 435 |
|
| 436 |
import pycurl |
| 437 |
from io import BytesIO |
| 438 |
|
| 439 |
c = pycurl.Curl() |
| 440 |
c.setopt(c.URL, 'https://httpbin.org/put') |
| 441 |
|
| 442 |
c.setopt(c.UPLOAD, 1) |
| 443 |
data = '{"json":true}' |
| 444 |
# READDATA requires an IO-like object; a string is not accepted |
| 445 |
buffer = BytesIO(data.encode('utf-8')) |
| 446 |
c.setopt(c.READDATA, buffer) |
| 447 |
|
| 448 |
c.perform() |
| 449 |
c.close() |
| 450 |
|
| 451 |
This code is available as ``examples/quickstart/put_buffer.py``. |
| 452 |
|
| 453 |
.. _curl_formadd page: https://curl.haxx.se/libcurl/c/curl_formadd.html |
| 454 |
.. _certifi: https://pypi.org/project/certifi/ |