6 nghttp2 offers some high level Python API to C library. The bindings
7 currently provide HPACK compressor and decompressor classes and HTTP/2
10 The extension module is called ``nghttp2``.
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``).
21 .. py:class:: HDDeflater(hd_table_bufsize_max=DEFLATE_MAX_HEADER_TABLE_SIZE)
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.
34 .. py:method:: deflate(headers)
36 Deflates the *headers*. The *headers* must be sequence of tuple
37 of name/value pair, which are byte strings (not unicode string).
39 This method returns the deflated header block in byte string.
40 Raises the exception if any error occurs.
42 .. py:method:: set_no_refset(no_refset)
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
49 .. py:method:: change_table_size(hd_table_bufsize_max)
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.
56 Raises the exception if any error occurs.
58 .. py:method:: get_hd_table()
60 Returns copy of current dynamic header table.
62 The following example shows how to deflate header name/value pairs:
64 .. code-block:: python
66 import binascii, nghttp2
68 deflater = nghttp2.HDDeflater()
70 res = deflater.deflate([(b'foo', b'bar'),
73 print(binascii.b2a_hex(res))
76 .. py:class:: HDInflater()
78 This class is used to perform header decompression.
80 .. py:method:: inflate(data)
82 Inflates the deflated header block *data*. The *data* must be
85 Raises the exception if any error occurs.
87 .. py:method:: change_table_size(hd_table_bufsize_max)
89 Changes header table size to *hd_table_bufsize_max* byte.
91 Raises the exception if any error occurs.
93 .. py:method:: get_hd_table()
95 Returns copy of current dynamic header table.
97 The following example shows how to inflate deflated header block:
99 .. code-block:: python
101 deflater = nghttp2.HDDeflater()
103 data = deflater.deflate([(b'foo', b'bar'),
106 inflater = nghttp2.HDInflater()
108 hdrs = inflater.inflate(data)
113 .. py:function:: print_hd_table(hdtable)
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.
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.
124 .. py:data:: DEFAULT_HEADER_TABLE_SIZE
126 The default header table size, which is 4096 as per HTTP/2
129 .. py:data:: DEFLATE_MAX_HEADER_TABLE_SIZE
131 The default header table size for deflater. The initial value
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::
145 $ ./configure PYTHON=/usr/bin/python3.4
147 .. py:class:: HTTP2Server(address, RequestHandlerClass, ssl=None)
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.
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
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`.
162 To disable SSL/TLS, omit *ssl* or specify ``None``.
164 .. py:method:: serve_forever()
166 Runs server and processes incoming requests forever.
168 .. py:class:: BaseRequestHandler(http2, stream_id)
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
174 The first callback method invoked is :py:meth:`on_headers()`. It is
175 called when HEADERS frame, which includes request header fields, is
178 If request has request body, :py:meth:`on_data()` is invoked for
179 each chunk of received data chunk.
181 When whole request is received, :py:meth:`on_request_done()` is
184 When stream is closed, :py:meth:`on_close()` is called.
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()`.
190 The application can push resource using :py:meth:`push()` method.
191 It must be used before :py:meth:`send_response()` call.
193 A :py:class:`BaseRequestHandler` has the following instance
196 .. py:attribute:: client_address
198 Contains a tuple of the form ``(host, port)`` referring to the
201 .. py:attribute:: stream_id
203 Stream ID of this stream
205 .. py:attribute:: scheme
207 Scheme of the request URI. This is a value of ``:scheme``
210 .. py:attribute:: method
212 Method of this stream. This is a value of ``:method`` header
215 .. py:attribute:: host
217 This is a value of ``:authority`` or ``host`` header field.
219 .. py:attribute:: path
221 This is a value of ``:path`` header field.
223 A :py:class:`BaseRequestHandler` has the following methods:
225 .. py:method:: on_headers()
227 Called when request HEADERS is arrived. By default, this method
230 .. py:method:: on_data(data)
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.
236 .. py:method:: on_request_done()
238 Called when whole request was received. By default, this method
241 .. py:method:: on_close(error_code)
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.
247 .. py:method:: send_response(status=200, headers=None, body=None)
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
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
262 Raises the exception if any error occurs.
264 .. py:method:: push(path, method='GET', request_headers=None, status=200, headers=None, body=None)
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.
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.
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
286 Returns an instance of ``RequestHandlerClass`` specified in
287 :py:class:`HTTP2Server` constructor for the pushed resource.
289 Raises the exception if any error occurs.
291 The following example illustrates :py:class:`HTTP2Server` and
292 :py:class:`BaseRequestHandler` usage:
294 .. code-block:: python
296 #!/usr/bin/env python
301 class Handler(nghttp2.BaseRequestHandler):
303 def on_headers(self):
304 self.push(path='/css/style.css',
305 request_headers = [('content-type', 'text/css')],
307 body='body{margin:0;}')
309 self.send_response(status=200,
310 headers = [('content-type', 'text/plain')],
311 body=io.BytesIO(b'nghttp2-python FTW'))
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')
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()