[Tutor] Using 'requests' + 'with statement' in Python 3.4.1
Peter Otten
__peter__ at web.de
Fri Sep 19 22:32:41 CEST 2014
Juan Christian wrote:
> On Fri, Sep 19, 2014 at 4:30 PM, Peter Otten <__peter__ at web.de> wrote:
>>
>> Well, you import closing from the stdlib with
>>
>> from contextlib import closing
>>
>> and then proceed to write your own closing
>>
>> @contextmanager
>> def closing(thing):
>> try:
>> yield thing
>> finally:
>> thing.close()
>>
>> At the moment my advice would be: forget about closing and the with-
>> statement. They are great to solve a problem you don't have (here).
>
>
> So, just do as you said in the post above, 'status["steamrep_scammer"] =
> "steamrep_scammer" in api' and use a single try-expect in the outer
> requests.get() ?
That would be a reasonable approach. Note that if there are multiple
possible exceptions that you want to handle with the same reaction you can
use a single try...except. Example:
def check_backpacktf(steamID64):
try:
data = download_data()
status = extract_status from_data(data)
except (DownloadFailed, MissingData):
status = default_status()
return status
Also to keep in mind for the occasion when you are going to reinvestigate
`with`:
with open("not-there") as f:
data = f.read()
This will throw an exception, and `with` offers no way to intercept with
that as __enter__() has not been called yet.
More information about the Tutor
mailing list