しかし、非同期でリンプしているため、スレッドまたはgeventを使用して非同期要求を実行することが可能です。
リクエストを書いたのと同じ著者であるgrequestsを書きました。 gevent +リクエストのみを使用します。 トピックを長く延期することはせず、このライブラリに関する詳細な情報を提供します。
Grequests- 通常のリクエストの非同期ラッパーです。
多くのURLに対して定期的なPOSTリクエストを作成しましょう:
import grequests with open("C:\\path\\urls.txt") as werewolves: array = [row.strip() for row in werewolves] params = {'a':'b', 'c':'d'} rs = [grequests.post(u, data=params) for u in array] for r in grequests.imap(rs, size=16) print(r[0].status_code, r[0].url)
すべてが非常に単純で、ライブラリがインポートされ、ファイルが読み取り用に開かれ、リストが作成され、params変数に値a:b、c:dが割り当てられます。
次に、POSTリクエスト自体を処理するrs変数を作成します。r変数については、grequests.mapを作成します([rs]、size =は非同期値で、値が大きいほど、httpリクエストはより速く実行されますが、16以上を設定しても意味がありません) 。
これで、すべての引数をr変数に、つまりgrequests.imap()で渡したので、通常のリクエストと同様にこの変数を操作できます。
そして、すべてのステータスコード、URLアドレスを表示する必要がある最後のステップは、rsもリストとして機能します。これは、タイプごとのインデックスエラーを回避するために行います。
TypeError: 'Response' object does not support indexing
このエラーのトレースバックですべてが順調に進む場合は、オプションをお勧めします。
def exception_handlerr(request, exception): print("Request failed", request.url) import grequests with open("C:\\path\\urls.txt") as werewolves: array = [row.strip() for row in werewolves] params = {'a':'b', 'c':'d'} rs = [grequests.post(u, data=params) for u in array] for r in grequests.map([rs], size=16, exception_handler=exception_handlerr) print(r[0].status_code, r[0].url)
次に、インデックスエラーを回避するために、変数rをリストとして参照します。
私たちが取った主なステップ。 サーバーを「タンク」できます。 ただし、このライブラリには超越的な非同期性はありません。 Aiohttpをご覧ください 。
また、grequestsの例外についても話したいと思います。 grequestsはリクエストからのエラークラスを使用しないため、次のように使用します。
def send(self, **kwargs): """ Prepares request based on parameter passed to constructor and optional ``kwargs```. Then sends request and saves response to :attr:`response` :returns: ``Response`` """ merged_kwargs = {} merged_kwargs.update(self.kwargs) merged_kwargs.update(kwargs) try: self.response = self.session.request(self.method, self.url, **merged_kwargs) except Exception as e: self.exception = e self.traceback = traceback.format_exc() return self
exception_handlerを使用してキャッチします。
def exception_handlerr(request, exception): print("Request failed", request.url) # print(str(exception))
完全なソースコード:
def exception_handlerr(request, exception): print("Request failed", request.url) import grequests with open("C:\\path\\urls.txt") as werewolves: array = [row.strip() for row in werewolves] params = {'a':'b', 'c':'d'} rs = [grequests.post(u, data=params) for u in array] for r in grequests.map([rs], size=16, exception_handler=exception_handlerr) print(r.status_code, r.url)
したがって、完全に自信を持ってエラーをキャッチできます。
GETリクエストでは、すべてがPOSTリクエストと同じくらい簡単です:
def exception_handlerr(request, exception): print("Request failed", request.url) import grequests with open("C:\\path\\urls.txt") as werewolves: array = [row.strip() for row in werewolves] rs = [grequests.get(u) for u in array] for r in grequests.map([rs], size=16, exception_handler=exception_handlerr) print(r.status_code, r.url)
→ ソースコードgrequests
→ リクエストのドキュメント
良い一日を!