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