Consuming HTTP Services in Python Transcripts
Chapter: HTTP services with Python builtins
Lecture: Python 3: Blog explorer: Adding a post with urllib.request
0:01 Well a read only blog explorer is kind of interesting,
0:04 but really the idea was that we could do all he crud operations, right,
0:07 so let's work on add post.
0:09 So just like we saw before, there is no urllib,
0:11 but there is a urllib.request which has a request class in it,
0:15 and here we are going to allocate some data, let's go look at the signature of this one,
0:19 so you can see we can pass url the data, the headers,
0:21 the origin host and most importantly, because there is a lot of flexibility
0:26 we can now pass an explicit method, okay, great.
0:30 So we are going to come over here, we are going to do the url,
0:33 we are going to do the json string, we are going to do the headers
0:36 but we are also going to set the method to post, explicitly and then again,
0:41 like before request.url open and it's going to go along more or less the same.
0:45 So let's go and create a post, we're going to see what's here,
0:51 okay, and we have this post comes from Python 2,
0:54 let's do one it's says that this post comes from Python 3,
0:59 content, it's going to be viewed 100 times,
1:02 oh yes, okay so the post data should be bytes,
1:04 not iterable strings, so that is pretty interesting, how are we going to solve that?
1:11 Well, let me take a step back here, and we are going to say data,
1:16 let's just call it data for now so let's go over here
1:19 and say data= and this is what we had before,
1:22 in Python 2 the difference between bytes and strings was not very strong,
1:26 what we can do though is we can say I'd like to take this string
1:29 and turn it into a particular byte array based on the encoding that we are expecting,
1:34 so probably he best choice here is to say I want to encode this using utf8
1:40 that is probably our best shot for the right encoding for this server, let's try it again.
1:44 Okay, just make sure that we got only our Python 2 one here,
1:49 so we are going to say something like this, from Python 3
1:53 so we are going to add Python 3, this is going to be new content
1:57 and this is going to be 1002.
1:59 Great, so now that we sent a byte array for our data,
2:02 everything worked great and we got back our newly created object
2:05 with the server side generated id and we can even list it,
2:08 we should see it right there along with the other one.
2:11 Perfect, and it seems to be turning a little bit higher
2:14 than the Python 2 version of this post which is kind of cool, right?