requests: Add context manager for response object.#1121
Open
Gadgetoid wants to merge 1 commit into
Open
Conversation
Signed-off-by: Phil Howard <github@gadgetoid.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When accessing
response.rawit's not always obvious you should callresponse.close()to close and free the socket. Since lwIP has a five socket limit by default this can very quickly result in cryptic ENOMEM errors.A context manager is widely understood to handle freeing resources on exit and permits the following, Pythonic pattern without leaking open sockets:
While I came up with this idea and wrote this code independently , this PR transpired to be partially a dupe of #278 but I have excluded the iteration features in favour of a clean, concise change in the hope it would be easier to consider.
Testing
This is a minor change adding well understood magic methods, I did a cursory check to make sure it would work.
Trade-offs and Alternatives
This is a very minor change for a lot of potential utility, though without associated documentation changes it's unlikely to receive adoption.
CPython's "requests" library has the concept of a
Session, which includes a context manager at a lower level, and implements get/post etc using a transient Session. This is a potentially useful concept in MicroPython because the time cost of re-opening a socket when TLS is involved is prohibitive - 300-400ms. I'm currently using a completely custom HTTP library to avoid this.This change also has some minor functional overlap with
urllib urequest'surlopenwhich is sometimes favoured for streaming requests.Generative AI
I did not use generative AI tools when creating this PR.