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

Joel Goldstick joel.goldstick at gmail.com
Fri Sep 19 19:47:27 CEST 2014


On Fri, Sep 19, 2014 at 1:30 PM, Juan Christian
<juan0christian at gmail.com> wrote:
> This part of my code isn't working:
>
> def check_backpacktf(steamID64):
> with requests.get(''.join([BACKPACKTF, steamID64])) as response:

I'm not sure why my reply mangled your indents, but can you check to
see that your "".join() is getting what you think it should?
> 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?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com


More information about the Tutor mailing list