Debian Codegraph @

doc/callbacks.rst

raw
1 .. _callbacks:
2
3 Callbacks
4 =========
5
6 For more fine-grained control, libcurl allows a number of callbacks to be
7 associated with each connection. In pycurl, callbacks are defined using the
8 ``setopt()`` method for Curl objects with options ``WRITEFUNCTION``,
9 ``READFUNCTION``, ``HEADERFUNCTION``, ``PROGRESSFUNCTION``,
10 ``XFERINFOFUNCTION``, ``IOCTLFUNCTION``, ``DEBUGFUNCTION``,
11 ``PREREQFUNCTION``, ``TRAILERFUNCTION``, ``RESOLVER_START_FUNCTION``,
12 ``FNMATCH_FUNCTION``, ``HSTSREADFUNCTION`` or ``HSTSWRITEFUNCTION``.
13 These options correspond to the libcurl options with ``CURLOPT_``
14 prefix removed. A callback in pycurl must be either a regular Python
15 function, a class method or an extension type function.
16
17 There are some limitations to some of the options which can be used
18 concurrently with the pycurl callbacks compared to the libcurl callbacks.
19 This is to allow different callback functions to be associated with different
20 Curl objects. More specifically, ``WRITEDATA`` cannot be used with
21 ``WRITEFUNCTION``, ``READDATA`` cannot be used with ``READFUNCTION``,
22 ``WRITEHEADER`` cannot be used with ``HEADERFUNCTION``.
23 In practice, these limitations can be overcome by having a
24 callback function be a class instance method and rather use the class
25 instance attributes to store per object data such as files used in the
26 callbacks.
27
28 The signature of each callback used in PycURL is documented below.
29
30
31 Error Reporting
32 ---------------
33
34 PycURL callbacks are invoked as follows:
35
36 Python application -> ``perform()`` -> libcurl (C code) -> Python callback
37
38 Because callbacks are invoked by libcurl, they should not raise exceptions
39 on failure but instead return appropriate values indicating failure.
40 The documentation for individual callbacks below specifies expected success and
41 failure return values.
42
43 Unhandled exceptions propagated out of Python callbacks will be intercepted
44 by PycURL or the Python runtime. This will fail the callback with a
45 generic failure status, in turn failing the ``perform()`` operation.
46 A failing ``perform()`` will raise ``pycurl.error``, but the error code
47 used depends on the specific callback.
48
49 ``KeyboardInterrupt`` and other ``BaseException`` subclasses (for example, ``SystemExit``)
50 are handled specially: if they are raised inside a callback, they are preserved and re-raised
51 to the caller instead of being converted into a ``pycurl.error``.
52
53 Rich context information like exception objects can be stored in various ways,
54 for example the following example stores OPENSOCKET callback exception on the
55 Curl object::
56
57 import pycurl, random, socket
58
59 class ConnectionRejected(Exception):
60 pass
61
62 def opensocket(curl, purpose, curl_address):
63 # always fail
64 curl.exception = ConnectionRejected('Rejecting connection attempt in opensocket callback')
65 return pycurl.SOCKET_BAD
66
67 # the callback must create a socket if it does not fail,
68 # see examples/opensocketexception.py
69
70 c = pycurl.Curl()
71 c.setopt(c.URL, 'http://pycurl.io')
72 c.exception = None
73 c.setopt(c.OPENSOCKETFUNCTION,
74 lambda purpose, address: opensocket(c, purpose, address))
75
76 try:
77 c.perform()
78 except pycurl.error as e:
79 if e.args[0] == pycurl.E_COULDNT_CONNECT and c.exception:
80 print(c.exception)
81 else:
82 print(e)
83
84
85 WRITEFUNCTION
86 -------------
87
88 .. function:: WRITEFUNCTION(byte string) -> number of characters written
89
90 Callback for writing data. Corresponds to `CURLOPT_WRITEFUNCTION`_
91 in libcurl.
92
93 On Python 3, the argument is of type ``bytes``.
94
95 The ``WRITEFUNCTION`` callback may return the number of bytes written.
96 If this number is not equal to the size of the byte string, this signifies
97 an error and libcurl will abort the request. Returning ``None`` is an
98 alternate way of indicating that the callback has consumed all of the
99 string passed to it and, hence, succeeded.
100
101 `write_test.py test`_ shows how to use ``WRITEFUNCTION``.
102
103
104 Example: Callbacks for document header and body
105 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
106
107 This example prints the header data to stderr and the body data to stdout.
108 Also note that neither callback returns the number of bytes written. For
109 WRITEFUNCTION and HEADERFUNCTION callbacks, returning None implies that all
110 bytes where written.
111
112 ::
113
114 ## Callback function invoked when body data is ready
115 def body(buf):
116 # Print body data to stdout
117 import sys
118 sys.stdout.write(buf)
119 # Returning None implies that all bytes were written
120
121 ## Callback function invoked when header data is ready
122 def header(buf):
123 # Print header data to stderr
124 import sys
125 sys.stderr.write(buf)
126 # Returning None implies that all bytes were written
127
128 c = pycurl.Curl()
129 c.setopt(pycurl.URL, "http://www.python.org/")
130 c.setopt(pycurl.WRITEFUNCTION, body)
131 c.setopt(pycurl.HEADERFUNCTION, header)
132 c.perform()
133
134
135 HEADERFUNCTION
136 --------------
137
138 .. function:: HEADERFUNCTION(byte string) -> number of characters written
139
140 Callback for writing received headers. Corresponds to
141 `CURLOPT_HEADERFUNCTION`_ in libcurl.
142
143 On Python 3, the argument is of type ``bytes``.
144
145 The ``HEADERFUNCTION`` callback may return the number of bytes written.
146 If this number is not equal to the size of the byte string, this signifies
147 an error and libcurl will abort the request. Returning ``None`` is an
148 alternate way of indicating that the callback has consumed all of the
149 string passed to it and, hence, succeeded.
150
151 `header_test.py test`_ shows how to use ``WRITEFUNCTION``.
152
153
154 READFUNCTION
155 ------------
156
157 .. function:: READFUNCTION(number of characters to read) -> byte string
158
159 Callback for reading data. Corresponds to `CURLOPT_READFUNCTION`_ in
160 libcurl.
161
162 The callback must return either a C-contiguous object supporting
163 the buffer protocol (e.g. `bytes`, `bytearray`, `memoryview`, or a
164 C-contiguous `numpy` array) or a Unicode string consisting of ASCII code
165 points only.
166
167 In addition, ``READFUNCTION`` may return ``READFUNC_ABORT`` or
168 ``READFUNC_PAUSE``. See the libcurl documentation for an explanation
169 of these values.
170
171 The `file_upload.py example`_ in the distribution contains example code for
172 using ``READFUNCTION``.
173
174
175 .. _SEEKFUNCTION:
176
177 SEEKFUNCTION
178 ------------
179
180 .. function:: SEEKFUNCTION(offset, origin) -> status
181
182 Callback for seek operations. Corresponds to `CURLOPT_SEEKFUNCTION`_
183 in libcurl.
184
185 ``origin`` is ``0`` (beginning), ``1`` (current position) or ``2`` (end).
186
187 Return one of:
188
189 - ``SEEKFUNC_OK`` (seek succeeded)
190 - ``SEEKFUNC_FAIL`` (hard failure)
191 - ``SEEKFUNC_CANTSEEK`` (seek not possible; libcurl may fall back)
192
193
194 IOCTLFUNCTION
195 -------------
196
197 .. function:: IOCTLFUNCTION(ioctl cmd) -> status
198
199 Callback for I/O operations. Corresponds to `CURLOPT_IOCTLFUNCTION`_
200 in libcurl.
201
202 *Note:* this callback is deprecated. Use :ref:`SEEKFUNCTION <SEEKFUNCTION>` instead.
203
204
205 DEBUGFUNCTION
206 -------------
207
208 .. function:: DEBUGFUNCTION(debug message type, debug message byte string) -> None
209
210 Callback for debug information. Corresponds to `CURLOPT_DEBUGFUNCTION`_
211 in libcurl.
212
213 *Changed in version 7.19.5.2:* The second argument to a ``DEBUGFUNCTION``
214 callback is now of type ``bytes`` on Python 3. Previously the argument was
215 of type ``str``.
216
217 `debug_test.py test`_ shows how to use ``DEBUGFUNCTION``.
218
219
220 Example: Debug callbacks
221 ~~~~~~~~~~~~~~~~~~~~~~~~
222
223 This example shows how to use the debug callback. The debug message type is
224 an integer indicating the type of debug message. The VERBOSE option must be
225 enabled for this callback to be invoked.
226
227 ::
228
229 def test(debug_type, debug_msg):
230 print("debug(%d): %s" % (debug_type, debug_msg))
231
232 c = pycurl.Curl()
233 c.setopt(pycurl.URL, "https://curl.haxx.se/")
234 c.setopt(pycurl.VERBOSE, 1)
235 c.setopt(pycurl.DEBUGFUNCTION, test)
236 c.perform()
237
238
239 PROGRESSFUNCTION
240 ----------------
241
242 .. function:: PROGRESSFUNCTION(download total, downloaded, upload total, uploaded) -> status
243
244 Callback for progress meter. Corresponds to `CURLOPT_PROGRESSFUNCTION`_
245 in libcurl.
246
247 ``PROGRESSFUNCTION`` receives amounts as floating point arguments to the
248 callback. Since libcurl 7.32.0 ``PROGRESSFUNCTION`` is deprecated;
249 ``XFERINFOFUNCTION`` should be used instead which receives amounts as
250 long integers.
251
252 ``NOPROGRESS`` option must be set for False libcurl to invoke a
253 progress callback, as PycURL by default sets ``NOPROGRESS`` to True.
254
255
256 XFERINFOFUNCTION
257 ----------------
258
259 .. function:: XFERINFOFUNCTION(download total, downloaded, upload total, uploaded) -> status
260
261 Callback for progress meter. Corresponds to `CURLOPT_XFERINFOFUNCTION`_
262 in libcurl.
263
264 ``XFERINFOFUNCTION`` receives amounts as long integers.
265
266 ``NOPROGRESS`` option must be set for False libcurl to invoke a
267 progress callback, as PycURL by default sets ``NOPROGRESS`` to True.
268
269
270 Example: Download/upload progress callback
271 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
272
273 This example shows how to use the progress callback. When downloading a
274 document, the arguments related to uploads are zero, and vice versa.
275
276 ::
277
278 ## Callback function invoked when download/upload has progress
279 def progress(download_t, download_d, upload_t, upload_d):
280 print("Total to download", download_t)
281 print("Total downloaded", download_d)
282 print("Total to upload", upload_t)
283 print("Total uploaded", upload_d)
284
285 c = pycurl.Curl()
286 c.setopt(c.URL, "http://slashdot.org/")
287 c.setopt(c.NOPROGRESS, False)
288 c.setopt(c.XFERINFOFUNCTION, progress)
289 c.perform()
290
291
292 OPENSOCKETFUNCTION
293 ------------------
294
295 .. function:: OPENSOCKETFUNCTION(purpose, address) -> int
296
297 Callback for opening sockets. Corresponds to
298 `CURLOPT_OPENSOCKETFUNCTION`_ in libcurl.
299
300 *purpose* is a ``SOCKTYPE_*`` value.
301
302 *address* is a `namedtuple`_ with ``family``, ``socktype``, ``protocol``
303 and ``addr`` fields, per `CURLOPT_OPENSOCKETFUNCTION`_ documentation.
304
305 *addr* is an object representing the address. Currently the following
306 address families are supported:
307
308 - ``AF_INET``: *addr* is a 2-tuple of ``(host, port)``.
309 - ``AF_INET6``: *addr* is a 4-tuple of ``(host, port, flow info, scope id)``.
310 - ``AF_UNIX``: *addr* is a byte string containing path to the Unix socket.
311
312 Availability: Unix.
313
314 This behavior matches that of Python's `socket module`_.
315
316 The callback should return a socket object, a socket file descriptor
317 or a Python object with a ``fileno`` property containing the socket
318 file descriptor.
319
320 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
321 as the value or by calling :ref:`unsetopt <unsetopt>`.
322
323 `open_socket_cb_test.py test`_ shows how to use ``OPENSOCKETFUNCTION``.
324
325 *Changed in version 7.21.5:* Previously, the callback received ``family``,
326 ``socktype``, ``protocol`` and ``addr`` parameters (``purpose`` was
327 not passed and ``address`` was flattened). Also, ``AF_INET6`` addresses
328 were exposed as 2-tuples of ``(host, port)`` rather than 4-tuples.
329
330 *Changed in version 7.19.3:* ``addr`` parameter added to the callback.
331
332
333 CLOSESOCKETFUNCTION
334 -------------------
335
336 .. function:: CLOSESOCKETFUNCTION(curlfd) -> int
337
338 Callback for setting socket options. Corresponds to
339 `CURLOPT_CLOSESOCKETFUNCTION`_ in libcurl.
340
341 *curlfd* is the file descriptor to be closed.
342
343 The callback should return an ``int``.
344
345 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
346 as the value or by calling :ref:`unsetopt <unsetopt>`.
347
348 `close_socket_cb_test.py test`_ shows how to use ``CLOSESOCKETFUNCTION``.
349
350
351 SOCKOPTFUNCTION
352 ---------------
353
354 .. function:: SOCKOPTFUNCTION(curlfd, purpose) -> int
355
356 Callback for setting socket options. Corresponds to `CURLOPT_SOCKOPTFUNCTION`_
357 in libcurl.
358
359 *curlfd* is the file descriptor of the newly created socket.
360
361 *purpose* is a ``SOCKTYPE_*`` value.
362
363 The callback should return an ``int``.
364
365 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
366 as the value or by calling :ref:`unsetopt <unsetopt>`.
367
368 `sockopt_cb_test.py test`_ shows how to use ``SOCKOPTFUNCTION``.
369
370
371 SSH_KEYFUNCTION
372 ---------------
373
374 .. function:: SSH_KEYFUNCTION(known_key, found_key, match) -> int
375
376 Callback for known host matching logic. Corresponds to
377 `CURLOPT_SSH_KEYFUNCTION`_ in libcurl.
378
379 *known_key* and *found_key* are instances of ``KhKey`` class which is a
380 `namedtuple`_ with ``key`` and ``keytype`` fields, corresponding to
381 libcurl's ``struct curl_khkey``::
382
383 KhKey = namedtuple('KhKey', ('key', 'keytype'))
384
385 The *key* field of ``KhKey`` is ``bytes``. *keytype* is an ``int``.
386
387 *known_key* may be ``None`` when there is no known matching host key.
388
389 ``SSH_KEYFUNCTION`` callback should return a ``KHSTAT_*`` value.
390
391 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
392 as the value or by calling :ref:`unsetopt <unsetopt>`.
393
394 `ssh_key_cb_test.py test`_ shows how to use ``SSH_KEYFUNCTION``.
395
396
397 TIMERFUNCTION
398 -------------
399
400 .. function:: TIMERFUNCTION(timeout_ms) -> int | None
401
402 Callback for installing a timer requested by libcurl. Corresponds to
403 `CURLMOPT_TIMERFUNCTION`_.
404
405 The application should arrange for a non-repeating timer to fire in
406 ``timeout_ms`` milliseconds, at which point the application should call
407 either :ref:`socket_action <multi-socket_action>` or
408 :ref:`perform <multi-perform>`. See the `CURLMOPT_TIMERFUNCTION`_ docs
409 for the special values of ``timeout_ms``.
410
411 Return ``0`` or ``None`` for success, or ``-1`` to abort all
412 in-progress transfers in the multi handle. Exceptions raised in the
413 callback are printed to stderr and treated as ``-1``.
414
415 See ``examples/multi-socket_action-select.py`` for an example program
416 that uses the timer function and the socket function.
417
418
419 SOCKETFUNCTION
420 --------------
421
422 .. function:: SOCKETFUNCTION(what, sock_fd, multi, socketp) -> int | None
423
424 Callback notifying the application about activity on libcurl sockets.
425 Corresponds to `CURLMOPT_SOCKETFUNCTION`_.
426
427 Note that the PycURL callback takes ``what`` as the first argument and
428 ``sock_fd`` as the second argument, whereas the libcurl callback takes
429 ``sock_fd`` as the first argument and ``what`` as the second argument.
430
431 *what* is one of ``pycurl.POLL_IN``, ``POLL_OUT``, ``POLL_INOUT`` or
432 ``POLL_REMOVE``; see the `CURLMOPT_SOCKETFUNCTION`_ docs for their
433 meaning.
434
435 The ``userp`` ("private callback pointer") argument, as described in the
436 ``CURLMOPT_SOCKETFUNCTION`` documentation, is set to the ``CurlMulti``
437 instance.
438
439 The ``socketp`` ("private socket pointer") argument, as described in the
440 ``CURLMOPT_SOCKETFUNCTION`` documentation, is set to the value provided
441 to the :ref:`assign <multi-assign>` method for the corresponding
442 ``sock_fd``, or ``None`` if no value was assigned.
443
444 Return ``0`` or ``None`` for success, or ``-1`` to abort all
445 in-progress transfers in the multi handle. Exceptions raised in the
446 callback are printed to stderr and treated as ``-1``.
447
448 See ``examples/multi-socket_action-select.py`` for an example program
449 that uses the timer function and the socket function.
450
451
452 PREREQFUNCTION
453 ---------------
454
455 .. function:: PREREQFUNCTION(conn_primary_ip, conn_local_ip, conn_primary_port, conn_local_port) -> int
456
457 Callback called when a connection has been established, but before a
458 request has been made. Corresponds to `CURLOPT_PREREQFUNCTION`_ in libcurl.
459
460 *conn_primary_ip* is the primary IP address of the remote server established with this connection (as a string).
461
462 *conn_local_ip* is the originating IP address for this connection (as a string).
463
464 *conn_primary_port* is the primary port number on the remote server established with this connection.
465
466 *conn_local_port* is the originating port number for this connection.
467
468 The callback should return an ``int``, which must be either ``PREREQFUNC_OK`` (on success) or ``PREREQFUNC_ABORT`` to cause the transfer to fail with result ``ABORTED_BY_CALLBACK``.
469
470 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
471 as the value or by calling :ref:`unsetopt <unsetopt>`.
472
473 `prereq_cb_test.py test`_ shows how to use ``PREREQFUNCTION``.
474
475
476 TRAILERFUNCTION
477 ---------------
478
479 .. function:: TRAILERFUNCTION() -> list of strings or None
480
481 Callback for supplying HTTP trailing headers on chunked uploads.
482 Corresponds to `CURLOPT_TRAILERFUNCTION`_ in libcurl.
483
484 The callback takes no arguments and should return either ``None``
485 (no trailing headers) or a list or tuple of header strings in
486 ``"Name: value"`` form. The same rules apply to these strings as
487 do to ``HTTPHEADER`` entries.
488
489 Raising an exception from the callback, or returning any other type,
490 causes the transfer to fail with ``TRAILERFUNC_ABORT``.
491
492 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
493 as the value or by calling :ref:`unsetopt <unsetopt>`.
494
495
496 RESOLVER_START_FUNCTION
497 -----------------------
498
499 .. function:: RESOLVER_START_FUNCTION() -> int
500
501 Callback invoked before each name resolution. Corresponds to
502 `CURLOPT_RESOLVER_START_FUNCTION`_ in libcurl.
503
504 The callback takes no arguments. Return ``0`` (or ``None``) to let the
505 resolution proceed; return any non-zero value to abort the transfer.
506
507 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
508 as the value or by calling :ref:`unsetopt <unsetopt>`.
509
510
511 FNMATCH_FUNCTION
512 ----------------
513
514 .. function:: FNMATCH_FUNCTION(pattern, string) -> int
515
516 Callback for wildcard matching used by the FTP wildcard transfer
517 feature. Corresponds to `CURLOPT_FNMATCH_FUNCTION`_ in libcurl.
518
519 *pattern* and *string* are both ``bytes``.
520
521 The callback should return one of:
522
523 - ``FNMATCHFUNC_MATCH`` (pattern matched)
524 - ``FNMATCHFUNC_NOMATCH`` (pattern did not match)
525 - ``FNMATCHFUNC_FAIL`` (error during matching; aborts the transfer)
526
527 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
528 as the value or by calling :ref:`unsetopt <unsetopt>`.
529
530
531 HSTSWRITEFUNCTION
532 -----------------
533
534 .. function:: HSTSWRITEFUNCTION(entry, index) -> int
535
536 Callback for persisting the in-memory HSTS cache. Corresponds to
537 `CURLOPT_HSTSWRITEFUNCTION`_ in libcurl. Requires ``HSTS_CTRL`` to be
538 set to ``CURLHSTS_ENABLE``.
539
540 *entry* is an ``HstsEntry`` `namedtuple`_ with ``host``, ``expire``
541 and ``include_subdomains`` fields::
542
543 HstsEntry = namedtuple('HstsEntry',
544 ('host', 'expire', 'include_subdomains'))
545
546 *host* is ``bytes``. *expire* is a tz-aware ``datetime`` in UTC, or
547 ``None`` when the entry never expires. *include_subdomains* is ``bool``.
548
549 *index* is an ``HstsIndex`` `namedtuple`_ indicating progress through
550 the cache::
551
552 HstsIndex = namedtuple('HstsIndex', ('index', 'total'))
553
554 The callback should return ``CURLSTS_OK`` (entry accepted),
555 ``CURLSTS_DONE`` (stop iterating) or ``CURLSTS_FAIL`` (error).
556 Returning ``None`` is equivalent to ``CURLSTS_OK``.
557
558 libcurl invokes the callback during ``perform()`` and during handle
559 cleanup; exceptions raised inside the callback while the handle is
560 being cleaned up are written to :py:data:`sys.unraisablehook` and
561 do not propagate.
562
563 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
564 as the value or by calling :ref:`unsetopt <unsetopt>`.
565
566
567 HSTSREADFUNCTION
568 ----------------
569
570 .. function:: HSTSREADFUNCTION() -> HstsEntry or None
571
572 Callback for preloading the in-memory HSTS cache. Corresponds to
573 `CURLOPT_HSTSREADFUNCTION`_ in libcurl. Requires ``HSTS_CTRL`` to be
574 set to ``CURLHSTS_ENABLE``.
575
576 The callback takes no arguments. It is invoked repeatedly until it
577 returns ``None``.
578
579 Return ``None`` to signal there are no more entries
580 (``CURLSTS_DONE``), or an ``HstsEntry`` (or any 3-tuple) where:
581
582 - *host* is ``bytes`` or an ASCII ``str``.
583 - *expire* is a ``datetime`` or ``None``. ``None`` means the entry
584 never expires. Aware datetimes are converted to UTC; naive
585 datetimes are interpreted as UTC.
586 - *include_subdomains* is any truthy/falsy value.
587
588 Raising an exception or returning anything else causes the transfer
589 to fail with ``CURLSTS_FAIL``.
590
591 The callback may be unset by calling :ref:`setopt <setopt>` with ``None``
592 as the value or by calling :ref:`unsetopt <unsetopt>`.
593
594
595 WebSocket callback receive (libcurl 7.86.0 or later)
596 ----------------------------------------------------
597
598 libcurl supports two WebSocket usage models: *detached mode*
599 (``CONNECT_ONLY=2`` plus ``ws_send`` / ``ws_recv``, documented on the
600 :ref:`Curl object <curlobject>`) and *callback-receive mode*, where
601 libcurl drives the transfer and delivers each received frame chunk
602 through the ordinary ``WRITEFUNCTION`` callback. No separate callback
603 registration is required — set ``WRITEFUNCTION`` on a ``ws://`` /
604 ``wss://`` URL, leave ``CONNECT_ONLY`` unset, and call
605 :ref:`perform <perform>` as you would for any other transfer.
606 ``perform()`` blocks for the full lifetime of the WebSocket connection
607 and returns when the peer closes (or the transfer otherwise terminates),
608 so the server side must have a predictable end condition.
609
610 Inside the callback, :py:meth:`pycurl.Curl.ws_meta` returns a ``WsFrame``
611 namedtuple (``age``, ``flags``, ``offset``, ``bytesleft``, ``len``)
612 describing the chunk currently being delivered. The ``flags`` field is
613 a bitmask of ``WS_TEXT``, ``WS_BINARY``, ``WS_CONT``, ``WS_PING``,
614 ``WS_PONG``, ``WS_CLOSE``, and ``WS_OFFSET``.
615
616 libcurl's ``curl_ws_meta()`` returns ``NULL`` outside the valid
617 callback context; PycURL maps that to Python ``None``. The same
618 ``ws_meta()`` method is safe to call after ``perform()`` has returned
619 (it simply returns ``None``) and in detached mode (likewise).
620
621 Calling :py:meth:`ws_send` or :py:meth:`ws_close` from inside the
622 ``WRITEFUNCTION`` is allowed: libcurl treats the call as a blocking send
623 and returns only once the frame has been fully written (or an error
624 occurs). ``CURLE_AGAIN`` / ``BlockingIOError`` semantics do not apply in
625 this context. That relaxation applies only inside the callback itself;
626 calls from another thread while ``perform()`` is running are still
627 rejected. :py:meth:`ws_recv` and :py:meth:`ws_recv_into` remain
628 detached-only and still raise ``pycurl.error`` while ``perform()`` is
629 running.
630
631 Example::
632
633 import pycurl
634
635 c = pycurl.Curl()
636
637 def on_ws_chunk(data):
638 meta = c.ws_meta() # valid only inside this callback
639 if meta is not None and meta.flags & pycurl.WS_TEXT:
640 print("text chunk:", data)
641 c.ws_send(b"ack", pycurl.WS_BINARY) # blocking send
642 return len(data)
643
644 c.setopt(c.URL, "wss://example.com/socket")
645 c.setopt(c.WRITEFUNCTION, on_ws_chunk)
646 c.perform() # blocks until peer closes
647 c.close()
648
649 `ws_callback.py example`_ is a complete runnable version.
650
651
652 .. _CURLOPT_HEADERFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_HEADERFUNCTION.html
653 .. _CURLOPT_WRITEFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
654 .. _CURLOPT_READFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_READFUNCTION.html
655 .. _CURLOPT_PROGRESSFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html
656 .. _CURLOPT_XFERINFOFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_XFERINFOFUNCTION.html
657 .. _CURLOPT_DEBUGFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_DEBUGFUNCTION.html
658 .. _CURLOPT_SEEKFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_SEEKFUNCTION.html
659 .. _CURLOPT_IOCTLFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_IOCTLFUNCTION.html
660 .. _file_upload.py example: https://github.com/pycurl/pycurl/blob/master/examples/file_upload.py
661 .. _write_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/write_test.py
662 .. _header_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/header_test.py
663 .. _debug_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/debug_test.py
664 .. _CURLOPT_SSH_KEYFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_SSH_KEYFUNCTION.html
665 .. _namedtuple: https://docs.python.org/library/collections.html#collections.namedtuple
666 .. _CURLOPT_SOCKOPTFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_SOCKOPTFUNCTION.html
667 .. _sockopt_cb_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/sockopt_cb_test.py
668 .. _ssh_key_cb_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/ssh_key_cb_test.py
669 .. _CURLOPT_CLOSESOCKETFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_CLOSESOCKETFUNCTION.html
670 .. _close_socket_cb_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/close_socket_cb_test.py
671 .. _CURLOPT_OPENSOCKETFUNCTION: https://curl.haxx.se/libcurl/c/CURLOPT_OPENSOCKETFUNCTION.html
672 .. _open_socket_cb_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/open_socket_cb_test.py
673 .. _socket module: https://docs.python.org/library/socket.html
674 .. _CURLMOPT_TIMERFUNCTION: https://curl.se/libcurl/c/CURLMOPT_TIMERFUNCTION.html
675 .. _CURLMOPT_SOCKETFUNCTION: https://curl.se/libcurl/c/CURLMOPT_SOCKETFUNCTION.html
676 .. _CURLOPT_PREREQFUNCTION: https://curl.se/libcurl/c/CURLOPT_PREREQFUNCTION.html
677 .. _prereq_cb_test.py test: https://github.com/pycurl/pycurl/blob/master/tests/prereq_cb_test.py
678 .. _CURLOPT_TRAILERFUNCTION: https://curl.se/libcurl/c/CURLOPT_TRAILERFUNCTION.html
679 .. _CURLOPT_RESOLVER_START_FUNCTION: https://curl.se/libcurl/c/CURLOPT_RESOLVER_START_FUNCTION.html
680 .. _CURLOPT_FNMATCH_FUNCTION: https://curl.se/libcurl/c/CURLOPT_FNMATCH_FUNCTION.html
681 .. _CURLOPT_HSTSREADFUNCTION: https://curl.se/libcurl/c/CURLOPT_HSTSREADFUNCTION.html
682 .. _CURLOPT_HSTSWRITEFUNCTION: https://curl.se/libcurl/c/CURLOPT_HSTSWRITEFUNCTION.html
683 .. _ws_callback.py example: https://github.com/pycurl/pycurl/blob/master/examples/ws_callback.py