Imported Upstream version 1.0.0
[platform/upstream/nghttp2.git] / doc / sources / python-apiref.rst
1 Python API Reference
2 ====================
3
4 .. py:module:: nghttp2
5
6 nghttp2 offers some high level Python API to C library.  The bindings
7 currently provide HPACK compressor and decompressor classes and HTTP/2
8 server class.
9
10 The extension module is called ``nghttp2``.
11
12 ``make`` will build the bindings.  The target Python version is
13 determined by configure script.  If the detected Python version is not
14 what you expect, specify a path to Python executable in ``PYTHON``
15 variable as an argument to configure script (e.g., ``./configure
16 PYTHON=/usr/bin/python3.4``).
17
18 HPACK API
19 ---------
20
21 .. py:class:: HDDeflater(hd_table_bufsize_max=DEFLATE_MAX_HEADER_TABLE_SIZE)
22
23    This class is used to perform header compression.  The
24    *hd_table_bufsize_max* limits the usage of header table in the
25    given amount of bytes.  The default value is
26    :py:data:`DEFLATE_MAX_HEADER_TABLE_SIZE`.  This is necessary
27    because the deflater and inflater share the same amount of header
28    table and the inflater decides that number.  The deflater may not
29    want to use all header table size because of limited memory
30    availability.  In that case, *hd_table_bufsize_max* can be used to
31    cap the upper limit of table size whatever the header table size is
32    chosen by the inflater.
33
34    .. py:method:: deflate(headers)
35
36       Deflates the *headers*. The *headers* must be sequence of tuple
37       of name/value pair, which are byte strings (not unicode string).
38
39       This method returns the deflated header block in byte string.
40       Raises the exception if any error occurs.
41
42    .. py:method:: set_no_refset(no_refset)
43
44       Tells the deflater not to use reference set if *no_refset* is
45       evaluated to ``True``.  If that happens, on each subsequent
46       invocation of :py:meth:`deflate()`, deflater will clear up
47       refersent set.
48
49    .. py:method:: change_table_size(hd_table_bufsize_max)
50
51       Changes header table size to *hd_table_bufsize_max* byte.  if
52       *hd_table_bufsize_max* is strictly larger than
53       ``hd_table_bufsize_max`` given in constructor,
54       ``hd_table_bufsize_max`` is used as header table size instead.
55
56       Raises the exception if any error occurs.
57
58    .. py:method:: get_hd_table()
59
60       Returns copy of current dynamic header table.
61
62 The following example shows how to deflate header name/value pairs:
63
64 .. code-block:: python
65
66    import binascii, nghttp2
67
68    deflater = nghttp2.HDDeflater()
69
70    res = deflater.deflate([(b'foo', b'bar'),
71                            (b'baz', b'buz')])
72
73    print(binascii.b2a_hex(res))
74
75
76 .. py:class:: HDInflater()
77
78    This class is used to perform header decompression.
79
80    .. py:method:: inflate(data)
81
82       Inflates the deflated header block *data*. The *data* must be
83       byte string.
84
85       Raises the exception if any error occurs.
86
87    .. py:method:: change_table_size(hd_table_bufsize_max)
88
89       Changes header table size to *hd_table_bufsize_max* byte.
90
91       Raises the exception if any error occurs.
92
93    .. py:method:: get_hd_table()
94
95       Returns copy of current dynamic header table.
96
97 The following example shows how to inflate deflated header block:
98
99 .. code-block:: python
100
101    deflater = nghttp2.HDDeflater()
102
103    data = deflater.deflate([(b'foo', b'bar'),
104                             (b'baz', b'buz')])
105
106    inflater = nghttp2.HDInflater()
107
108    hdrs = inflater.inflate(data)
109
110    print(hdrs)
111
112
113 .. py:function:: print_hd_table(hdtable)
114
115    Convenient function to print *hdtable* to the standard output.  The
116    *hdtable* is the one retrieved by
117    :py:meth:`HDDeflater.get_hd_table()` or
118    :py:meth:`HDInflater.get_hd_table()`.  This function does not work
119    if header name/value cannot be decoded using UTF-8 encoding.
120
121    In output, ``s=N`` means the entry occupies ``N`` bytes in header
122    table.  If ``r=y``, then the entry is in the reference set.
123
124 .. py:data:: DEFAULT_HEADER_TABLE_SIZE
125
126    The default header table size, which is 4096 as per HTTP/2
127    specification.
128
129 .. py:data:: DEFLATE_MAX_HEADER_TABLE_SIZE
130
131    The default header table size for deflater.  The initial value
132    is 4096.
133
134 HTTP/2 servers
135 --------------
136
137 .. note::
138
139    We use :py:mod:`asyncio` for HTTP/2 server classes.  Therefore,
140    Python 3.4 or later is required to use these objects.  To
141    explicitly configure nghttp2 build to use Python 3.4, specify the
142    ``PYTHON`` variable to the path to Python 3.4 executable when
143    invoking configure script like this::
144
145        $ ./configure PYTHON=/usr/bin/python3.4
146
147 .. py:class:: HTTP2Server(address, RequestHandlerClass, ssl=None)
148
149    This class builds on top of the :py:mod:`asyncio` event loop.  On
150    construction, *RequestHandlerClass* must be given, which must be a
151    subclass of :py:class:`BaseRequestHandler` class.
152
153    The *address* must be a tuple of hostname/IP address and port to
154    bind.  If hostname/IP address is ``None``, all interfaces are
155    assumed.
156
157    To enable SSL/TLS, specify instance of :py:class:`ssl.SSLContext`
158    in *ssl*.  Before passing *ssl* to
159    :py:func:`BaseEventLoop.create_server`, ALPN protocol identifiers
160    are set using :py:meth:`ssl.SSLContext.set_npn_protocols`.
161
162    To disable SSL/TLS, omit *ssl* or specify ``None``.
163
164    .. py:method:: serve_forever()
165
166       Runs server and processes incoming requests forever.
167
168 .. py:class:: BaseRequestHandler(http2, stream_id)
169
170    The class is used to handle the single HTTP/2 stream.  By default,
171    it does not nothing.  It must be subclassed to handle each event
172    callback method.
173
174    The first callback method invoked is :py:meth:`on_headers()`. It is
175    called when HEADERS frame, which includes request header fields, is
176    arrived.
177
178    If request has request body, :py:meth:`on_data()` is invoked for
179    each chunk of received data chunk.
180
181    When whole request is received, :py:meth:`on_request_done()` is
182    invoked.
183
184    When stream is closed, :py:meth:`on_close()` is called.
185
186    The application can send response using :py:meth:`send_response()`
187    method.  It can be used in :py:meth:`on_headers()`,
188    :py:meth:`on_data()` or :py:meth:`on_request_done()`.
189
190    The application can push resource using :py:meth:`push()` method.
191    It must be used before :py:meth:`send_response()` call.
192
193    A :py:class:`BaseRequestHandler` has the following instance
194    variables:
195
196    .. py:attribute:: client_address
197
198       Contains a tuple of the form ``(host, port)`` referring to the
199       client's address.
200
201    .. py:attribute:: stream_id
202
203       Stream ID of this stream
204
205    .. py:attribute:: scheme
206
207       Scheme of the request URI.  This is a value of ``:scheme``
208       header field.
209
210    .. py:attribute:: method
211
212       Method of this stream.  This is a value of ``:method`` header
213       field.
214
215    .. py:attribute:: host
216
217       This is a value of ``:authority`` or ``host`` header field.
218
219    .. py:attribute:: path
220
221       This is a value of ``:path`` header field.
222
223    .. py:attribute:: headers
224
225       Request header fields.
226
227    A :py:class:`BaseRequestHandler` has the following methods:
228
229    .. py:method:: on_headers()
230
231       Called when request HEADERS is arrived.  By default, this method
232       does nothing.
233
234    .. py:method:: on_data(data)
235
236       Called when a chunk of request body *data* is arrived.  This
237       method will be called multiple times until all data are
238       received.  By default, this method does nothing.
239
240    .. py:method:: on_request_done()
241
242       Called when whole request was received.  By default, this method
243       does nothing.
244
245    .. py:method:: on_close(error_code)
246
247       Called when stream is about to close.  The *error_code*
248       indicates the reason of closure.  If it is ``0``, the stream is
249       going to close without error.
250
251    .. py:method:: send_response(status=200, headers=None, body=None)
252
253       Send response.  The *status* is HTTP status code.  The *headers*
254       is additional response headers.  The *:status* header field will
255       be appended by the library.  The *body* is the response body.
256       It could be ``None`` if response body is empty.  Or it must be
257       instance of either ``str``, ``bytes``, :py:class:`io.IOBase` or
258       callable, called body generator, which takes one parameter,
259       size.  The body generator generates response body.  It can pause
260       generation of response so that it can wait for slow backend data
261       generation.  When invoked, it should return tuple, byte string
262       at most size length and flag.  The flag is either
263       :py:data:`DATA_OK`, :py:data:`DATA_EOF` or
264       :py:data:`DATA_DEFERRED`.  For non-empty byte string and it is
265       not the last chunk of response, :py:data:`DATA_OK` must be
266       returned as flag.  If this is the last chunk of the response
267       (byte string could be ``None``), :py:data:`DATA_EOF` must be
268       returned as flag.  If there is no data available right now, but
269       additional data are anticipated, return tuple (``None``,
270       :py:data:`DATA_DEFERRED`).  When data arrived, call
271       :py:meth:`resume()` and restart response body transmission.
272
273       Only the body generator can pause response body generation;
274       instance of :py:class:`io.IOBase` must not block.
275
276       If instance of ``str`` is specified as *body*, it will be
277       encoded using UTF-8.
278
279       The *headers* is a list of tuple of the form ``(name,
280       value)``. The ``name`` and ``value`` can be either byte string
281       or unicode string.  In the latter case, they will be encoded
282       using UTF-8.
283
284       Raises the exception if any error occurs.
285
286    .. py:method:: push(path, method='GET', request_headers=None, status=200, headers=None, body=None)
287
288       Push a specified resource.  The *path* is a path portion of
289       request URI for this resource.  The *method* is a method to
290       access this resource.  The *request_headers* is additional
291       request headers to access this resource.  The ``:scheme``,
292       ``:method``, ``:authority`` and ``:path`` are appended by the
293       library.  The ``:scheme`` and ``:authority`` are inherited from
294       request header fields of the associated stream.
295
296       The *status* is HTTP status code.  The *headers* is additional
297       response headers.  The ``:status`` header field is appended by
298       the library.  The *body* is the response body.  It has the same
299       semantics of *body* parameter of :py:meth:`send_response()`.
300
301       The headers and request_headers are a list of tuple of the form
302       ``(name, value)``. The ``name`` and ``value`` can be either byte
303       string or unicode string.  In the latter case, they will be
304       encoded using UTF-8.
305
306       Returns an instance of ``RequestHandlerClass`` specified in
307       :py:class:`HTTP2Server` constructor for the pushed resource.
308
309       Raises the exception if any error occurs.
310
311    .. py:method:: resume()
312
313       Signals the restarting of response body transmission paused by
314       ``DATA_DEFERRED`` from the body generator (see
315       :py:meth:`send_response()` about the body generator).  It is not
316       an error calling this method while response body transmission is
317       not paused.
318
319 .. py:data:: DATA_OK
320
321    ``DATA_OK`` indicates non empty data is generated from body generator.
322
323 .. py:data:: DATA_EOF
324
325    ``DATA_EOF`` indicates the end of response body.
326
327 .. py:data:: DATA_DEFERRED
328
329    ``DATA_DEFERRED`` indicates that data are not available right now
330    and response should be paused.
331
332 The following example illustrates :py:class:`HTTP2Server` and
333 :py:class:`BaseRequestHandler` usage:
334
335 .. code-block:: python
336
337     #!/usr/bin/env python
338
339     import io, ssl
340
341     import nghttp2
342
343     class Handler(nghttp2.BaseRequestHandler):
344
345         def on_headers(self):
346             self.push(path='/css/style.css',
347                       request_headers = [('content-type', 'text/css')],
348                       status=200,
349                       body='body{margin:0;}')
350
351             self.send_response(status=200,
352                                headers = [('content-type', 'text/plain')],
353                                body=io.BytesIO(b'nghttp2-python FTW'))
354
355     ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
356     ctx.options = ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3
357     ctx.load_cert_chain('server.crt', 'server.key')
358
359     # give None to ssl to make the server non-SSL/TLS
360     server = nghttp2.HTTP2Server(('127.0.0.1', 8443), Handler, ssl=ctx)
361     server.serve_forever()
362
363 The following example illustrates HTTP/2 server using asynchronous
364 response body generation.  This is simplified reverse proxy:
365
366 .. code-block:: python
367
368     #!/usr/bin/env python
369
370     import ssl
371     import os
372     import urllib
373     import asyncio
374     import io
375
376     import nghttp2
377
378     @asyncio.coroutine
379     def get_http_header(handler, url):
380         url = urllib.parse.urlsplit(url)
381         ssl = url.scheme == 'https'
382         if url.port == None:
383             if url.scheme == 'https':
384                 port = 443
385             else:
386                 port = 80
387         else:
388             port = url.port
389
390         connect = asyncio.open_connection(url.hostname, port, ssl=ssl)
391         reader, writer = yield from connect
392         req = 'GET {path} HTTP/1.0\r\n\r\n'.format(path=url.path or '/')
393         writer.write(req.encode('utf-8'))
394         # skip response header fields
395         while True:
396             line = yield from reader.readline()
397             line = line.rstrip()
398             if not line:
399                 break
400         # read body
401         while True:
402             b = yield from reader.read(4096)
403             if not b:
404                 break
405             handler.buf.write(b)
406         writer.close()
407         handler.buf.seek(0)
408         handler.eof = True
409         handler.resume()
410
411     class Body:
412         def __init__(self, handler):
413             self.handler = handler
414             self.handler.eof = False
415             self.handler.buf = io.BytesIO()
416
417         def generate(self, n):
418             buf = self.handler.buf
419             data = buf.read1(n)
420             if not data and not self.handler.eof:
421                 return None, nghttp2.DATA_DEFERRED
422             return data, nghttp2.DATA_EOF if self.handler.eof else nghttp2.DATA_OK
423
424     class Handler(nghttp2.BaseRequestHandler):
425
426         def on_headers(self):
427             body = Body(self)
428             asyncio.async(get_http_header(
429                 self, 'http://localhost' + self.path.decode('utf-8')))
430             self.send_response(status=200, body=body.generate)
431
432     ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
433     ctx.options = ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3
434     ctx.load_cert_chain('server.crt', 'server.key')
435
436     server = nghttp2.HTTP2Server(('127.0.0.1', 8443), Handler, ssl=ctx)
437     server.serve_forever()