client-python icon indicating copy to clipboard operation
client-python copied to clipboard

Unclosed Session/SSLSocket

Open sky-coding opened this issue 6 years ago • 5 comments

When I run the following python code with a debugger attached -

polygon_api = polygon.RESTClient()
response = polygon_api.stocks_equities_aggregates('AAPL', 30, 'minute', '2020-06-30', '2020-06-30')

I get a post-run warning from my debugger -

ResourceWarning: unclosed <ssl.SSLSocket type=SocketKind.SOCK_STREAM, raddr=('38.133.177.84', 443)>

But if I run -

polygon_api = polygon.RESTClient()
response = polygon_api.stocks_equities_aggregates('AAPL', 30, 'minute', '2020-06-30', '2020-06-30')
polygon_api._session.close()

The polygon client cleans up and my debugger is happy.

Looking into why this is, Session will only call its own close() from its __exit__ method, which is only called if the class is being used as a context manager (e.g. using with Session() as s: statement, as suggested by their docs) - and RESTClient is not using it in this manner, so close() is just never being called and resources are being left open.

sky-coding avatar Jul 01 '20 17:07 sky-coding

I got the same error. When I run individual python file in terminal, it works. But when I send request in background mode using Celery, I got following error.

raised unexpected: RecursionError('maximum recursion depth exceeded while calling a Python object',)

Achilles718611 avatar Jul 18 '20 04:07 Achilles718611

I could finally solve problem. This is related with dependency not this library self. I used celery and dnspython 2.0.0 caused error. I downgraded dnspython version to 1.16.0 and now it works.

Achilles718611 avatar Jul 18 '20 07:07 Achilles718611

@Achilles718611 I'm not using celery or dnspython, I still believe the issue to be RESTClient never calling the close() method on its Session. You may have just masked the issue by modifying upstream network behavior

sky-coding avatar Jul 20 '20 21:07 sky-coding

@sky-coding please look at #37 and see if this satisfies your needs. This should handle properly cleaning up the http resources used

jbonzo avatar Aug 23 '20 16:08 jbonzo

@jbonzo I pulled your branch and verified that the unclosed socket error is eliminated in the use case I provided when using RESTClient as a context manager (which you added support for). Thanks!

sky-coding avatar Aug 23 '20 20:08 sky-coding