Twisted Example Client: Post RequestsΒΆ
This example is a basic HTTP/2 client written for the Twisted asynchronous networking framework.
This client is fairly simple: it makes a hard-coded POST request to nghttp2.org/httpbin/post and prints out the response data, sending a file that is provided on the command line or the script itself. Its purpose is to demonstrate how to write a HTTP/2 client implementation that handles flow control.
1# -*- coding: utf-8 -*-
2"""
3post_request.py
4~~~~~~~~~~~~~~~
5
6A short example that demonstrates a client that makes POST requests to certain
7websites.
8
9This example is intended to demonstrate how to handle uploading request bodies.
10In this instance, a file will be uploaded. In order to handle arbitrary files,
11this example also demonstrates how to obey HTTP/2 flow control rules.
12
13Takes one command-line argument: a path to a file in the filesystem to upload.
14If none is present, uploads this file.
15"""
16from __future__ import print_function
17
18import mimetypes
19import os
20import sys
21
22from twisted.internet import reactor, defer
23from twisted.internet.endpoints import connectProtocol, SSL4ClientEndpoint
24from twisted.internet.protocol import Protocol
25from twisted.internet.ssl import optionsForClientTLS
26from h2.connection import H2Connection
27from h2.events import (
28 ResponseReceived, DataReceived, StreamEnded, StreamReset, WindowUpdated,
29 SettingsAcknowledged,
30)
31
32
33AUTHORITY = u'nghttp2.org'
34PATH = '/httpbin/post'
35
36
37class H2Protocol(Protocol):
38 def __init__(self, file_path):
39 self.conn = H2Connection()
40 self.known_proto = None
41 self.request_made = False
42 self.request_complete = False
43 self.file_path = file_path
44 self.flow_control_deferred = None
45 self.fileobj = None
46 self.file_size = None
47
48 def connectionMade(self):
49 """
50 Called by Twisted when the TCP connection is established. We can start
51 sending some data now: we should open with the connection preamble.
52 """
53 self.conn.initiate_connection()
54 self.transport.write(self.conn.data_to_send())
55
56 def dataReceived(self, data):
57 """
58 Called by Twisted when data is received on the connection.
59
60 We need to check a few things here. Firstly, we want to validate that
61 we actually negotiated HTTP/2: if we didn't, we shouldn't proceed!
62
63 Then, we want to pass the data to the protocol stack and check what
64 events occurred.
65 """
66 if not self.known_proto:
67 self.known_proto = self.transport.negotiatedProtocol
68 assert self.known_proto == b'h2'
69
70 events = self.conn.receive_data(data)
71
72 for event in events:
73 if isinstance(event, ResponseReceived):
74 self.handleResponse(event.headers)
75 elif isinstance(event, DataReceived):
76 self.handleData(event.data)
77 elif isinstance(event, StreamEnded):
78 self.endStream()
79 elif isinstance(event, SettingsAcknowledged):
80 self.settingsAcked(event)
81 elif isinstance(event, StreamReset):
82 reactor.stop()
83 raise RuntimeError("Stream reset: %d" % event.error_code)
84 elif isinstance(event, WindowUpdated):
85 self.windowUpdated(event)
86
87 data = self.conn.data_to_send()
88 if data:
89 self.transport.write(data)
90
91 def settingsAcked(self, event):
92 """
93 Called when the remote party ACKs our settings. We send a SETTINGS
94 frame as part of the preamble, so if we want to be very polite we can
95 wait until the ACK for that frame comes before we start sending our
96 request.
97 """
98 if not self.request_made:
99 self.sendRequest()
100
101 def handleResponse(self, response_headers):
102 """
103 Handle the response by printing the response headers.
104 """
105 for name, value in response_headers:
106 print("%s: %s" % (name.decode('utf-8'), value.decode('utf-8')))
107
108 print("")
109
110 def handleData(self, data):
111 """
112 We handle data that's received by just printing it.
113 """
114 print(data, end='')
115
116 def endStream(self):
117 """
118 We call this when the stream is cleanly ended by the remote peer. That
119 means that the response is complete.
120
121 Because this code only makes a single HTTP/2 request, once we receive
122 the complete response we can safely tear the connection down and stop
123 the reactor. We do that as cleanly as possible.
124 """
125 self.request_complete = True
126 self.conn.close_connection()
127 self.transport.write(self.conn.data_to_send())
128 self.transport.loseConnection()
129
130 def windowUpdated(self, event):
131 """
132 We call this when the flow control window for the connection or the
133 stream has been widened. If there's a flow control deferred present
134 (that is, if we're blocked behind the flow control), we fire it.
135 Otherwise, we do nothing.
136 """
137 if self.flow_control_deferred is None:
138 return
139
140 # Make sure we remove the flow control deferred to avoid firing it
141 # more than once.
142 flow_control_deferred = self.flow_control_deferred
143 self.flow_control_deferred = None
144 flow_control_deferred.callback(None)
145
146 def connectionLost(self, reason=None):
147 """
148 Called by Twisted when the connection is gone. Regardless of whether
149 it was clean or not, we want to stop the reactor.
150 """
151 if self.fileobj is not None:
152 self.fileobj.close()
153
154 if reactor.running:
155 reactor.stop()
156
157 def sendRequest(self):
158 """
159 Send the POST request.
160
161 A POST request is made up of one headers frame, and then 0+ data
162 frames. This method begins by sending the headers, and then starts a
163 series of calls to send data.
164 """
165 # First, we need to work out how large the file is.
166 self.file_size = os.stat(self.file_path).st_size
167
168 # Next, we want to guess a content-type and content-encoding.
169 content_type, content_encoding = mimetypes.guess_type(self.file_path)
170
171 # Now we can build a header block.
172 request_headers = [
173 (':method', 'POST'),
174 (':authority', AUTHORITY),
175 (':scheme', 'https'),
176 (':path', PATH),
177 ('user-agent', 'hyper-h2/1.0.0'),
178 ('content-length', str(self.file_size)),
179 ]
180
181 if content_type is not None:
182 request_headers.append(('content-type', content_type))
183
184 if content_encoding is not None:
185 request_headers.append(('content-encoding', content_encoding))
186
187 self.conn.send_headers(1, request_headers)
188 self.request_made = True
189
190 # We can now open the file.
191 self.fileobj = open(self.file_path, 'rb')
192
193 # We now need to send all the relevant data. We do this by checking
194 # what the acceptable amount of data is to send, and sending it. If we
195 # find ourselves blocked behind flow control, we then place a deferred
196 # and wait until that deferred fires.
197 self.sendFileData()
198
199 def sendFileData(self):
200 """
201 Send some file data on the connection.
202 """
203 # Firstly, check what the flow control window is for stream 1.
204 window_size = self.conn.local_flow_control_window(stream_id=1)
205
206 # Next, check what the maximum frame size is.
207 max_frame_size = self.conn.max_outbound_frame_size
208
209 # We will send no more than the window size or the remaining file size
210 # of data in this call, whichever is smaller.
211 bytes_to_send = min(window_size, self.file_size)
212
213 # We now need to send a number of data frames.
214 while bytes_to_send > 0:
215 chunk_size = min(bytes_to_send, max_frame_size)
216 data_chunk = self.fileobj.read(chunk_size)
217 self.conn.send_data(stream_id=1, data=data_chunk)
218
219 bytes_to_send -= chunk_size
220 self.file_size -= chunk_size
221
222 # We've prepared a whole chunk of data to send. If the file is fully
223 # sent, we also want to end the stream: we're done here.
224 if self.file_size == 0:
225 self.conn.end_stream(stream_id=1)
226 else:
227 # We've still got data left to send but the window is closed. Save
228 # a Deferred that will call us when the window gets opened.
229 self.flow_control_deferred = defer.Deferred()
230 self.flow_control_deferred.addCallback(self.sendFileData)
231
232 self.transport.write(self.conn.data_to_send())
233
234
235try:
236 filename = sys.argv[1]
237except IndexError:
238 filename = __file__
239
240options = optionsForClientTLS(
241 hostname=AUTHORITY,
242 acceptableProtocols=[b'h2'],
243)
244
245connectProtocol(
246 SSL4ClientEndpoint(reactor, AUTHORITY, 443, options),
247 H2Protocol(filename)
248)
249reactor.run()