正規表現で抜き出した複数の URL へのストリーム処理で GET をしたいのですが、ネットワーク系の経験があまりなく、以下で良いのか判断できていません。
for loop 中の id(resp) が変っています。この場合、resp が新しく作成されたタイミングで自動的に timeout するのでしょうか?
shadow variable を許す言語なので resp が破棄されるのが関数を出るタイミングだったと記憶しています。そのため、以下の Keep-Alive のセクションを読む限り大量に timeout していない resp が残ったままになるのではないかと考えています。
https://requests.readthedocs.io/en/latest/user/advanced/#session-objects
for loop の中で get() の後に resp.close() した方が良いのでしょうか?しかし、そのようにするとストリーミング処理した意味がなくなってしまうのではないかと思うのですが...
最後に他にサーバー側に負荷を掛けずに、もっと効率的に処理する方法などありましたらご指摘ください。
ses = requests.Session() resp = ses.get(self.URLS['short_ratio'], stream=True, timeout=3) resp.encoding = resp.apparent_encoding url_chars = '[0-9a-zA-Z\/\-\_]*' urls_xls = [] urls_xls += re.findall('{0}\.xls?'.format(url_chars), resp.text) for p in re.findall('{0}\d\d-archives-\d\d\.html?'.format(url_chars): resp = ses.get('{0}{1}'.format(self.BASE_URL, p), stream=True, timeout=3) print(id(ses), id(resp)) print(resp.cookies) resp.encoding = resp.apparent_encoding urls_xls += re.findall('{0}\.xls?'.format(url_chars), resp.text) resp.close() ses.close()
$ pytest-3 -s pandas_datareader/tests/test_tse.py ============================= test session starts ============================== platform linux -- Python 3.9.2, pytest-6.0.2, py-1.10.0, pluggy-0.13.0 rootdir: ************************************, configfile: setup.cfg collected 1 item pandas_datareader/tests/test_tse.py 140171185815120 140171185185648 <RequestsCookieJar[]> 140171185815120 140171185566768 <RequestsCookieJar[]> 140171185815120 140171185366880 <RequestsCookieJar[]> 140171185815120 140171185567056 <RequestsCookieJar[]> 140171185815120 140171185368752 <RequestsCookieJar[]> 140171185815120 140171185568448 <RequestsCookieJar[]> 140171185815120 140171185366880 <RequestsCookieJar[]> 140171185815120 140171185568736 <RequestsCookieJar[]> 140171185815120 140171185368752 <RequestsCookieJar[]> 140171185815120 140171185568688 <RequestsCookieJar[]> 140171185815120 140171185366880 <RequestsCookieJar[]> 140171185815120 140171185568688 <RequestsCookieJar[]> . ============================== 1 passed in 3.33s ===============================
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/01/09 02:18 編集
2023/01/09 02:25
2023/01/09 03:24