[Tutor] Using 'requests' + 'with statement' in Python 3.4.1

Peter Otten __peter__ at web.de
Fri Sep 19 20:15:27 CEST 2014


Juan Christian wrote:

> This part of my code isn't working:
> 
> def check_backpacktf(steamID64):
> with requests.get(''.join([BACKPACKTF, steamID64])) as response:
> status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value':
> 'Private or invalid', 'steamrep_scammer': False}
> 
> with response.json()['response']['players'][steamID64] as api:
> status['backpack_value'] = api['backpack_value'][GAME_ID]
> status['steamrep_scammer'] = bool(api['steamrep_scammer'])
> 
> return status
> 
> -----
> 
> Traceback (most recent call last):
>   File "C:\[...]\shark.py", line 98, in <module>
>     main(sys.argv[1])
>   File "C:\[...]\shark.py", line 93, in main
>     fetch_forum()
>   File "C:\[...]\shark.py", line 79, in fetch_forum
>     fetch_user(user_url)
>   File "C:\[...]\shark.py", line 42, in fetch_user
>     backpacktf = check_backpacktf(steamID64)
>   File "C:\[...]\shark.py", line 25, in check_backpacktf
>     with requests.get(''.join([BACKPACKTF, steamID64])) as response:
> AttributeError: __exit__
> 
> 
> I'm trying to use the 'with statement' to reduce the SLOC and make the
> code prettier. Using 'try-expect-finally' wouldn't be good, as I have more
> 3 or 4 functions like this one that call different sites. What's the
> problem? Can't I use requests that way?

Let's take a step back: if you were to write

> with requests.get(''.join([BACKPACKTF, steamID64])) as response:
> status = {'profile': ''.join([BACKPACKTF, steamID64]),'backpack_value':
> 'Private or invalid', 'steamrep_scammer': False}

using try-except-finally -- what would it look like? 




More information about the Tutor mailing list