[Tutor] Using 'requests' + 'with statement' in Python 3.4.1
Peter Otten
__peter__ at web.de
Fri Sep 19 20:53:05 CEST 2014
Juan Christian wrote:
> On Fri, Sep 19, 2014 at 3:15 PM, Peter Otten <__peter__ at web.de> wrote:
>>
>> 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?
>
>
> Well, this site API is ridiculous, they use JSON but let's get an example:
>
> When an user is banned this ' "backpack_tf_banned": null ' is added in the
> JSON, they better way would be that this entry was there all the time, and
> set true or false for it. Same goes for ' "steamrep_scammer": true ', it's
> only there when the user is indeed a scammer, but now the value is true
> and not null as in the other entry.
>
> That's why I need the try-expect, and I need it here:
>
> 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
>
> The part of the code you posted the try-expect is needed because I don't
> know if they have all Steam users in their DB, so the request.get() could
> broke.
If I understand you correctly you can test for the presence of a value.
Example:
api = response.json()['response']['players'][steamID64]
status["steamrep_scammer"] = "steamrep_scammer" in api
More information about the Tutor
mailing list