Python for the .NET developer Transcripts
Chapter: Course conclusion
Lecture: async and await review
0:00 One of the most amazing features
0:02 of C# is it's async and await framework
0:04 in the task parallel library.
0:06 And guess what? Python has it too!
0:08 Over here we're going to create a GET HTML function
0:12 and it's going to go over to my podcast
0:14 grab a episode number, use that as the URL
0:17 and then download that page
0:20 use a little bit of screen scraping after this
0:21 to figure out what the title is.
0:23 That's the demo that we did, anyway.
0:25 So we want this method to be able to run
0:27 alongside other methods, right?
0:29 Really, all you're doing is waiting
0:30 on the internet, waiting on the Python Server.
0:33 Why should your code go slow and do that one at a time?
0:36 You can send a bunch of those off.
0:37 So, here we're going to asynchronously define a method
0:41 get_html, and then we can use async and await
0:44 in the context.
0:45 In C# you just have await in the body of the method
0:48 but here we have async context managers.
0:51 Alright, so we have async with httpx.AasyncClient() as client
0:55 and the async part there
0:56 make sure that we asynchronously close
0:58 any pending network connections
1:00 with a keep alive or something like that.
1:02 Then we're going to call client.get.
1:05 That returns to coroutine that when we await it
1:07 is going to return a web response
1:10 and then we're just going to work with that from there.
1:11 That's the way we build async methods in Python.
1:15 Remember you have to manually manage the loop
1:17 and all of that stuff, it's a little bit cumbersome
1:20 so consider using the unsync library
1:23 to even more like C#s task per the library.