Usage and Migration Guide for Twilio's Python Helper Library 6.x
Deprecation notice: New functionality will only be added to the new library (Python Helper Library 6.x). The old library (5.x) is deprecated and Twilio will no longer provide bug fixes. Support might ask you to upgrade before debugging issues.
The Twilio Python Helper Library has undergone a number of changes from version 5.x to 6.x - we'll break down the major changes here to make migrating to the new version as painless as possible. If you're integrating Twilio in your Python app for the first time, you can skip straight to the install page.
Pythonのバージョンサポート
Version 6.x of the Python SDK requires at least Python version 2.7. It will work with later versions, including Python 3.x versions.
ライブラリーのインポート
twilio-python
5.xでは、クライアントは下記のようにインポートされていました:
from twilio.rest import TwilioRestClient from twilio.rest import TwilioLookupsClient from twilio.rest import TwilioTaskRouterClient ...
6.xでは、インポートが必要なオブジェクトは1つだけです。
from twilio.rest import Client
従来、ちょうどTwilioRestClient
で行なっていたように初期化を行えます。
from twilio.rest import Client client = Client('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'your_auth_token')
リソースへのアクセス
# Old call = client.account.calls('CA123xxx') # New call = client.api.v2010.calls('CA123xxx').fetch() ## OR call = client.calls('CA123xxx').fetch()
新しいライブラリーでは、TwilioのAPIサブドメイン(Lookups、Trunking、Monitorなど)は一級市民です。 またTwilio APIへのインスタンスを特定のAPIのバージョンにつなぎとめておくこともできるようになりました(すなわち、.v2010.
は常にAPIの2010-04-01バージョンとやりとりすることを保証します)。 こうすることで、ライブラリーの更新時にフルにアップグレードを行うことなく、コードの一部分のみを将来のバージョンに独立して移行することができます。
また、実際のCall
インスタンスの取得の最後でfetch
を呼び出す必要がある点にもお気づきでしょう。 これは、.calls('CAxxx')
が「コンテキスト」を返すためです。 これによって、その後fetch
を呼び出してインスタンスを、付随する全プロパティーを伴って受け取ることができます。 こうすることでネットワーク効率が向上し、ライブラリーが実際にHTTPインタラクションを処理するタイミングが明確になります。
> workspace = client.taskrouter.workspaces('WSxxx') #=> <WorkspaceContext ...> > workspace.fetch() #=> <WorkspaceInstance status='active'...>
Phone Numbers(電話番号)エンドポイント
バージョン5.xでは、IncomingPhoneNumbers
およびAvailablePhoneNumbers
はひとつのリソースにまとめられていました。
# Old numbers = client.account.phone_numbers.search(country_code='US', type='Local', area_code='415') if numbers: new_number = client.account.phone_numbers.create(phone_number=numbers[0].phone_number) print('Bought {}!'.format(new_number.phone_number))
バージョン6.xでは、他のエンドポイントとの一貫性を向上させるため、またある時点で実際にTwilio APIのどのエンドポイントとやりとりしているかをより明確にするため、2つのエンドポイントに分割されました。
numbers = client.api.available_phone_numbers('US').local.list(area_code='415') if numbers: new_number = client.incoming_phone_numbers.create(phone_number=numbers[0].phone_number) print('Bought {}!'.format(new_number.phone_number))
リソースの一覧
リソースの一覧を取得する方法が2種類になりました: list
とstream
です。
list
は、それが常に果たすべき仕事をします。 リソースのインスタンスを含むArray
を返します。
> client.api.messages.list() #=> [#<MessageInstance ..>, #<MessageInstance ..>, ...]
stream
はgenerator
を返します。 これはリソースの一覧を効率的にページ分けしてくれ、limit
の値で設定された数だけ(limit
が設定されていない場合、一覧全体のすべてのリソースを)リソースを出力します。
> for message in client.api.messages.stream(limit=5) > .. print(message.sid) MS111xxx MS222xxx MS333xxx MS444xxx MS555xxx
ページング
ライブラリーは自動でページング処理をしてくれるようになりました! list
およびstream
いずれの場合でも、取得したいインスタンスの数(limit
)、各ページで取得したい最大サイズ(page_size
)、および取得したいページの最大数(page_limit
)を指定できます。 これで、あとのことはライブラリーが(極力効率的に)処理してくれます。
for number in client.api.incoming_phone_numbers.stream(limit=3000, page_size=100): print(number.phone_number)
> len(client.conversations.completed.list(page_size=100, page_limit=10)) #=> 1000
正しい型
twilio-python
リソースは適切な型にシリアル化、逆シリアル化されるようになりました。 たとえば、バージョン5.xでは日付はstring
として表され、文字列を使用可能な型にシリアル化、逆シリアル化についてはユーザーに委ねられていました。 バージョン6.xでは、datetime
オブジェクトを使用します。
# Old feedback = client.account.calls.feedback_summary.create(start_date='2016-01-01', end_date='2016-01-05') feedback.start_date #=> "2016-01-01"
# New feedback = client.api.calls.feedback_summary.create(start_date=datetime(2016, 1, 1), end_date=datetime(2016, 1, 5)) feedback.start_date #=> datetime.datetime(2016, 1, 1, 0, 0)
構成可能なHTTPクライアント
独自のHTTPクライアントをTwilio
クライアントに接続できるようになりました!HttpClientインターフェイスに適合するラッパーを作成するだけです。 続いて、初期化済みのオブジェクトをTwilio
オブジェクトに渡します。
custom_client = MyCustomClient() client = Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'your_auth_token', http_client=custom_client)
See a complete example of creating a custom client in the Twilio helper library.
TwiML生成
下記のように、簡単なTwiMLを出力するため、呼び出しをチェインできるようになりました:
from twilio.twiml.voice_response import VoiceResponse def output_quick_polite_twiml(): return VoiceResponse().say('Hello!').hangup()
また、出力したいレスポンスの種類に応じて、2つのレスポンスタイプが存在することにも気づかれるでしょう。 VoiceResponse
は音声通話関連のすべての動詞、MessagingResponse
はメッセージ関連のすべての動詞に対するものです。
VoiceResponse
インスタンスのメソッドとして、音声通話関連の動詞が用意されています。 また、キーワード引数を使用してこれらの動詞に対して任意の属性を設定できます。 これらすべてはアンダースコア記法を使用します。
入れ子にされた動詞はwith
を使用する必要はなくなり、代わりにappend
が親要素となります。
同様の変更はMessagingResponse
にも当てはまります。
入れ子にされた例です:
APIリクエストのデバッグ
デバッグを容易にするため、ライブラリーでは内部的に使用されるリクエストおよびレスポンスのオブジェクトへのアクセスが行えるようになっています。 この機能はライブラリーに内蔵されている既定のHTTPクライアントに内蔵されています。
たとえば、下記のようにして直前のレスポンスのステータスコードを取得できます:
from twilio.rest import Client # put your own credentials here account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) client.messages.create(to="+14158675309", from_="+14258675310", body="Ahoy!") # Retrieve the status code of the last response from the HTTP client print(client.http_client.last_response.status_code)
例外
6.x has added more descriptive exception handlers.
To use it, import the TwilioRestException and catch it at the try-except
block.
from twilio.base.exceptions import TwilioRestException try: message = client.messages.create(to="+12316851234", from_="+15555555555", body="Hello there!") except TwilioRestException as e: # here you can implement you fallback code print(e)
関連トピックとサポート
すべてのクイックスタート、チュートリアル、およびAPIリファレンスのドキュメントには、古い5.xライブラリと新しい6.xライブラリの両方のサンプルコードが含まれています。 コピー&ペーストで活用できるサンプルが数多くあります。コピー&ペーストで活用できるサンプルが数多くあります。
The Twilio Python helper library is open source software. Please visit us on GitHub to view the source, open issues, or submit pull requests.
Finally, we are always ready to help. Just contact us directly for support.
ヘルプが必要ですか?
誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。