| 1 |
# -*- coding: utf-8 -*- |
| 2 |
""" |
| 3 |
post_request.py |
| 4 |
~~~~~~~~~~~~~~~ |
| 5 |
|
| 6 |
A short example that demonstrates a client that makes POST requests to certain |
| 7 |
websites. |
| 8 |
|
| 9 |
This example is intended to demonstrate how to handle uploading request bodies. |
| 10 |
In this instance, a file will be uploaded. In order to handle arbitrary files, |
| 11 |
this example also demonstrates how to obey HTTP/2 flow control rules. |
| 12 |
|
| 13 |
Takes one command-line argument: a path to a file in the filesystem to upload. |
| 14 |
If none is present, uploads this file. |
| 15 |
""" |
| 16 |
from __future__ import print_function |
| 17 |
|
| 18 |
import mimetypes |
| 19 |
import os |
| 20 |
import sys |
| 21 |
|
| 22 |
from twisted.internet import reactor, defer |
| 23 |
from twisted.internet.endpoints import connectProtocol, SSL4ClientEndpoint |
| 24 |
from twisted.internet.protocol import Protocol |
| 25 |
from twisted.internet.ssl import optionsForClientTLS |
| 26 |
from h2.connection import H2Connection |
| 27 |
from h2.events import ( |
| 28 |
ResponseReceived, DataReceived, StreamEnded, StreamReset, WindowUpdated, |
| 29 |
SettingsAcknowledged, |
| 30 |
) |
| 31 |
|
| 32 |
|
| 33 |
AUTHORITY = u'nghttp2.org' |
| 34 |
PATH = '/httpbin/post' |
| 35 |
|
| 36 |
|
| 37 |
class 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 |
('content-length', str(self.file_size)), |
| 178 |
] |
| 179 |
|
| 180 |
if content_type is not None: |
| 181 |
request_headers.append(('content-type', content_type)) |
| 182 |
|
| 183 |
if content_encoding is not None: |
| 184 |
request_headers.append(('content-encoding', content_encoding)) |
| 185 |
|
| 186 |
self.conn.send_headers(1, request_headers) |
| 187 |
self.request_made = True |
| 188 |
|
| 189 |
# We can now open the file. |
| 190 |
self.fileobj = open(self.file_path, 'rb') |
| 191 |
|
| 192 |
# We now need to send all the relevant data. We do this by checking |
| 193 |
# what the acceptable amount of data is to send, and sending it. If we |
| 194 |
# find ourselves blocked behind flow control, we then place a deferred |
| 195 |
# and wait until that deferred fires. |
| 196 |
self.sendFileData() |
| 197 |
|
| 198 |
def sendFileData(self): |
| 199 |
""" |
| 200 |
Send some file data on the connection. |
| 201 |
""" |
| 202 |
# Firstly, check what the flow control window is for stream 1. |
| 203 |
window_size = self.conn.local_flow_control_window(stream_id=1) |
| 204 |
|
| 205 |
# Next, check what the maximum frame size is. |
| 206 |
max_frame_size = self.conn.max_outbound_frame_size |
| 207 |
|
| 208 |
# We will send no more than the window size or the remaining file size |
| 209 |
# of data in this call, whichever is smaller. |
| 210 |
bytes_to_send = min(window_size, self.file_size) |
| 211 |
|
| 212 |
# We now need to send a number of data frames. |
| 213 |
while bytes_to_send > 0: |
| 214 |
chunk_size = min(bytes_to_send, max_frame_size) |
| 215 |
data_chunk = self.fileobj.read(chunk_size) |
| 216 |
self.conn.send_data(stream_id=1, data=data_chunk) |
| 217 |
|
| 218 |
bytes_to_send -= chunk_size |
| 219 |
self.file_size -= chunk_size |
| 220 |
|
| 221 |
# We've prepared a whole chunk of data to send. If the file is fully |
| 222 |
# sent, we also want to end the stream: we're done here. |
| 223 |
if self.file_size == 0: |
| 224 |
self.conn.end_stream(stream_id=1) |
| 225 |
else: |
| 226 |
# We've still got data left to send but the window is closed. Save |
| 227 |
# a Deferred that will call us when the window gets opened. |
| 228 |
self.flow_control_deferred = defer.Deferred() |
| 229 |
self.flow_control_deferred.addCallback(self.sendFileData) |
| 230 |
|
| 231 |
self.transport.write(self.conn.data_to_send()) |
| 232 |
|
| 233 |
|
| 234 |
try: |
| 235 |
filename = sys.argv[1] |
| 236 |
except IndexError: |
| 237 |
filename = __file__ |
| 238 |
|
| 239 |
options = optionsForClientTLS( |
| 240 |
hostname=AUTHORITY, |
| 241 |
acceptableProtocols=[b'h2'], |
| 242 |
) |
| 243 |
|
| 244 |
connectProtocol( |
| 245 |
SSL4ClientEndpoint(reactor, AUTHORITY, 443, options), |
| 246 |
H2Protocol(filename) |
| 247 |
) |
| 248 |
reactor.run() |