tizen 2.4 release
[external/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    A :py:class:`BaseRequestHandler` has the following methods:
224
225    .. py:method:: on_headers()
226
227       Called when request HEADERS is arrived.  By default, this method
228       does nothing.
229
230    .. py:method:: on_data(data)
231
232       Called when a chunk of request body *data* is arrived.  This
233       method will be called multiple times until all data are
234       received.  By default, this method does nothing.
235
236    .. py:method:: on_request_done()
237
238       Called when whole request was received.  By default, this method
239       does nothing.
240
241    .. py:method:: on_close(error_code)
242
243       Called when stream is about to close.  The *error_code*
244       indicates the reason of closure.  If it is ``0``, the stream is
245       going to close without error.
246
247    .. py:method:: send_response(status=200, headers=None, body=None)
248
249       Send response.  The *status* is HTTP status code.  The *headers*
250       is additional response headers.  The *:status* header field will
251       be appended by the library.  The *body* is the response body.
252       It could be ``None`` if response body is empty. Or it must be
253       instance of either ``str``, ``bytes`` or :py:class:`io.IOBase`.
254       If instance of ``str`` is specified, it will be encoded using
255       UTF-8.
256
257       The *headers* is a list of tuple of the form ``(name,
258       value)``. The ``name`` and ``value`` can be either byte string
259       or unicode string.  In the latter case, they will be encoded
260       using UTF-8.
261
262       Raises the exception if any error occurs.
263
264    .. py:method:: push(path, method='GET', request_headers=None, status=200, headers=None, body=None)
265
266       Push a specified resource.  The *path* is a path portion of
267       request URI for this resource.  The *method* is a method to
268       access this resource.  The *request_headers* is additional
269       request headers to access this resource.  The ``:scheme``,
270       ``:method``, ``:authority`` and ``:path`` are appended by the
271       library.  The ``:scheme`` and ``:authority`` are inherited from
272       request header fields of the associated stream.
273
274       The *status* is HTTP status code.  The *headers* is additional
275       response headers.  The ``:status`` header field is appended by
276       the library.  The *body* is the response body.  It could be
277       ``None`` if response body is empty.  Or it must be instance of
278       either ``str``, ``bytes`` or ``io.IOBase``.  If instance of
279       ``str`` is specified, it is encoded using UTF-8.
280
281       The headers and request_headers are a list of tuple of the form
282       ``(name, value)``. The ``name`` and ``value`` can be either byte
283       string or unicode string.  In the latter case, they will be
284       encoded using UTF-8.
285
286       Returns an instance of ``RequestHandlerClass`` specified in
287       :py:class:`HTTP2Server` constructor for the pushed resource.
288
289       Raises the exception if any error occurs.
290
291 The following example illustrates :py:class:`HTTP2Server` and
292 :py:class:`BaseRequestHandler` usage:
293
294 .. code-block:: python
295
296     #!/usr/bin/env python
297
298     import io, ssl
299     import nghttp2
300
301     class Handler(nghttp2.BaseRequestHandler):
302
303         def on_headers(self):
304             self.push(path='/css/style.css',
305                       request_headers = [('content-type', 'text/css')],
306                       status=200,
307                       body='body{margin:0;}')
308
309             self.send_response(status=200,
310                                headers = [('content-type', 'text/plain')],
311                                body=io.BytesIO(b'nghttp2-python FTW'))
312
313     ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
314     ctx.options = ssl.OP_ALL | ssl.OP_NO_SSLv2
315     ctx.load_cert_chain('server.crt', 'server.key')
316
317     # give None to ssl to make the server non-SSL/TLS
318     server = nghttp2.HTTP2Server(('127.0.0.1', 8443), Handler, ssl=ctx)
319     server.serve_forever()