How To Make ANY Function Asynchronous In Python 3.12
Summary
TLDRこのビデオチュートリアルでは、Pythonで非同期関数に変換する方法を学びます。特に、同期モジュールであるrequestsモジュールを例に、APIからJSONをリクエストする際にコードの実行をブロックしないようにする技術を紹介します。asyncioモジュールとasyncio.to_threadを使用して、任意の同期関数を非同期に実行する方法を実践的に説明します。さらに、複数のウェブサイトのステータスを非同期にチェックするサンプルスクリプトを作成する過程も解説します。このビデオは、非同期プログラミングの基礎を学びたい方にとって価値あるリソースです。
Takeaways
- 🐍 Pythonの非同期プログラミングの重要性を説明しています。
- 🌐 'requests'モジュールは同期的であり、コードのブロックを防ぎたい場合があると述べています。
- ⚙️ 'pip install requests'コマンドを使って、'requests'モジュールをインストールする方法を紹介しています。
- 🔍 'requests'から'response'タイプをインポートする方法を説明しています。
- 🖥️ 複数のウェブサイトのステータスを非同期でチェックするサンプルスクリプトを作成する過程を示しています。
- 🛠️ 'asyncio'と'from asyncio import task'をインポートすることで非同期関数を作成する方法を説明しています。
- 📡 'await asyncio.to_thread()'を使用して、任意の同期関数を非同期関数に変換する方法を説明しています。
- 🌍 特定のURLからステータスコードを非同期に取得する具体的な方法を示しています。
- 🏃 'async def main()'を使用して非同期タスクを実行し、結果を表示する方法を説明しています。
- ✨ Pythonで非同期プログラミングを活用することの便利さとパワフルさを強調しています。
Q & A
Pythonで非同期関数に変換する方法は何ですか?
-非同期IO(asyncio)モジュールの`to_thread`関数を使用して、同期関数を非同期関数に変換することができます。
`requests`モジュールを非同期で使用するにはどうすればよいですか?
-`asyncio.to_thread`を使って、`requests.get`関数を非同期に実行できます。
非同期関数で戻り値の型を指定するにはどうすればよいですか?
-関数の定義時に型注釈を使って戻り値の型を指定できます。例えば、`async def fetch_status(url: str) -> dict:`のようにします。
複数のウェブサイトのステータスを非同期でチェックするにはどうすればよいですか?
-非同期関数を定義し、`asyncio.create_task`を使ってそれぞれのウェブサイトのステータスを非同期にフェッチするタスクを作成します。
`asyncio.run`の役割は何ですか?
-`asyncio.run`は、非同期プログラムのメインエントリポイントを実行するために使用されます。
`asyncio.to_thread`の引数には何を指定しますか?
-実行したい関数、その関数に渡す引数、およびキーワード引数を指定します。
非同期関数の中で`await`キーワードの役割は何ですか?
-`await`キーワードは、非同期実行を待機し、その結果を取得するために使用されます。
非同期プログラミングで`Task`型の重要性は何ですか?
-`Task`型は、非同期に実行されるコルーチンを管理し、その結果を後で取得できるようにするために使用されます。
同期関数を非同期関数に変換するメリットは何ですか?
-ブロッキング操作を避け、アプリケーションのレスポンス性を向上させることができます。
非同期関数を使う際に、なぜ型注釈を使うのが良いとされていますか?
-型注釈を使用することで、関数の入力と戻り値の型が明確になり、コードの可読性と保守性が向上します。
Outlines
🐍 Python 非同期プログラミング入門
このビデオでは、Pythonで同期関数を非同期関数に変換する方法を紹介しています。特に、同期モジュールである'requests'モジュールを例に取り、APIからJSONデータを取得する際にコードのブロッキングを防ぐ方法に焦点を当てています。まず、'requests'モジュールのインストールから始め、その後、タイプアノテーションを使用し、非同期関数を作成する手順を詳細に説明しています。この関数は、ウェブサイトのステータスを非同期的にチェックする例として用いられ、'asyncio.to_thread'を使って任意の同期関数を非同期に変換する方法を示しています。最終的に、複数のウェブサイトのステータスを同時に取得するデモンストレーションが行われます。
🚀 非同期処理の実践と応用
このパートでは、非同期関数を使用して複数のウェブサイトのステータスを同時にチェックする方法を実践しています。具体的には、'asyncio'を使用して'apple.com'と'google.com'のステータスを非同期的に取得するデモが示されています。このプロセスでは、各ウェブサイトからのレスポンスを待つことなく、並行してリクエストを送信することが強調されています。また、非同期関数をより多くのタスクに適用する際の'gather'メソッドの使用も簡単に触れられています。最後に、視聴者にフィードバックを求める形でビデオが締めくくられています。
Mindmap
Keywords
💡非同期関数
💡asyncio
💡requests
💡ブロッキング
💡非同期I/O
💡タスク
💡async/await
💡ステータスコード
💡do_to_thread
💡gather
Highlights
I'm going to be teaching you how you can turn any synchronous function into an asynchronous function in Python
this is quite important because you might be working with a module such as the requests module which is a synchronous module which kind of sucks because if you're making a request for some Json from some sort of API you might not want that to block your code
we can create an asynchronous function or a co-routine and call it fetch status which will take a URL of type string and it's going to return to us a dictionary that we will Define now
this is the juicy part this is the way you can turn any synchronous function into an asynchronous function so await asyn iio do2 thread so that's going to St it on a separate thread
and it's as simple as that to turn any function into an asynchronous function
we were able to send the request for both of them and then once both of them got these status back we were able to use those statuses anyway it was as simple as that to turn a synchronous function into an asynchronous function
Transcripts
this video was brought to you by IND
dentle IO learning python Made Simple in
today's lesson I'm going to be teaching
you how you can turn any synchronous
function into an asynchronous function
in Python and this is quite important
because you might be working with a
module such as the requests module which
is a synchronous module which kind of
sucks because if you're making a request
for some Json from some sort of API you
might not want that to block your code
and anyway to get started we're going to
open up the terminal and type in PIP
install requests because that's what I'm
going to be using as an example for this
tutorial and once we have that we can
import requests and since I'm going to
be using a type annotation from requests
I'm going to import from
requests import the
response Now by this point you should be
quite familiar with how the requests
module actually works if you want a
response you would say response of type
response response equals
requests do getet and You' pass in your
url then once you get the response you
can call response. Json if you have an
API or you can even just get some other
information from that response once you
make that request but once again this is
a blocking request and what if we want
to check many websites or various
websites at the exact same time well to
demonstrate how we can do that I'm just
going to create a sample script that
checks whether multiple websites are
online and to do that before we actually
move any further I'm going to import
async iio and from asyn iio I'm going to
import the task type then down below we
can create an asynchronous function or a
co- routine and call it fetch
status and call it fetch status which
will take a URL of type string and it's
going to return to us
a dictionary that we will Define now
first of all we will add some beautiful
print message which will say fetching
status for and we will pass in the URL
then we can create our response of type
response which will equal a weight and
this is the juicy part this is the way
you can turn any synchronous function
into an asynchronous function so await
asyn iio do2 thread so that's going to
St it on a separate thread and as the
arguments we can pass in a function the
arguments for that function and the
keyword arguments for that function so
in this case since we're using get we're
going to call request.get and the only
argument we want to pass in really right
now is the URL so we're just going to
pass it in as is and for the arguments
you'd want to pass them in in order the
same way you would pass them in for get
if you hover over get you'll see that we
have the URL then we have the parameters
and so on now my Pi does complain to me
so what I do is pass in none for the
rest and my Pi does not complain anymore
and it's as simple as that to turn any
function into an asynchronous function
now that we have that there we can print
that we got it so I'm just going to
print done and we're going to return a
dictionary with the status which will be
the response. status code and which URL
that was
for now let's try to use this by
creating our main entry point So async
Def Main and that returns
none and first we'll create an apple
task and I don't like how little space
we have so I'll make some more Apple
task of type task which returns a
dictionary is going to equal an asyn i.
create task and we're going to pass in
Fetch status with the URL that we want
to fetch the status for in this case I'm
going to pass in
apple.com
but you can pass in whatever website you
want and then I'm going to duplicate
that and I'm going to call it Google
task and we're going to pass in
google.com then of course we need to
wait for these tasks to complete so
Apple status of type dictionary is going
to equal await Apple
task and the same thing goes for Google
task and of course we want different
names then all that's left for us to do
here is to display the results so print
Apple status and print Google
status and of course we need to run this
so if name is equal to
main we're going to run our script using
asyn
i.run with the main entry point being
our main function now with that we can
actually test this script by tapping on
run and what you should notice in the
console is that we're able to fetch the
status for both both of these websites
asynchronously we did not need to wait
for this one to complete before moving
on to Google we were able to send the
request for both of them and then once
both of them got these status back we
were able to use those statuses anyway
it was as simple as that to turn a
synchronous function into an
asynchronous function and yes you could
use gather if you have much if you have
many more websites you don't need to do
it one by one this is very labor
intensive if you have lots of tasks but
you get the point now you know how to
make functions that are not asynchronous
asynchronous that's another very
difficult sentence I don't know why I
decided to say it like that anyway
that's actually all I wanted to cover in
today's video do let me know in the
comment section down below whether this
helped with anything or whether you have
some added information I would love to
hear about that but otherwise as always
thanks for watching and I'll see you in
the next video
5.0 / 5 (0 votes)