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

Peter Otten __peter__ at web.de
Fri Sep 19 21:30:25 CEST 2014


Juan Christian wrote:

> This is the code using the contextlib (more than 105 lines):
> http://pastebin.com/jVhz7Ta6
> 
> But I'm getting another (super confusing) error now:
> 
> [#] [Tf2 inventory [W]CS GO Skins
>         Author: Pnoy Paragon << UNTIL HERE, OK!
> 
> Traceback (most recent call last):
>   File "C:\Users\Juan Christian\Desktop\trader.py", line 105, in <module>
>     main(sys.argv[1])
>   File "C:\Users\Juan Christian\Desktop\trader.py", line 100, in main
>     fetch_forum()
>   File "C:\Users\Juan Christian\Desktop\trader.py", line 86, in
>   fetch_forum
>     fetch_user(user_url)
>   File "C:\Users\Juan Christian\Desktop\trader.py", line 52, in fetch_user
>     backpacktf = check_backpacktf(steamID64)
>   File "C:\Users\Juan Christian\Desktop\trader.py", line 38, in
> check_backpacktf
>     with closing(response.json()['response']['players'][steamID64]) as
>     api:
>   File
> "C:\Development\Languages\Python34\lib\site-packages\requests-2.3.0-
py3.4.egg\requests\models.py",
> line 763, in j
> son
>     return json.loads(self.text, **kwargs)
>   File "C:\Development\Languages\Python34\lib\json\__init__.py", line 318,
> in loads
>     return _default_decoder.decode(s)
>   File "C:\Development\Languages\Python34\lib\json\decoder.py", line 343,
> in decode
>     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
>   File "C:\Development\Languages\Python34\lib\json\decoder.py", line 361,
> in raw_decode
>     raise ValueError(errmsg("Expecting value", s, err.value)) from None
> ValueError: Expecting value: line 1 column 1 (char 0)
> 
> 
> And SublimeText tells me 'Redefiniton of unused 'closing' from line 1'
> in @contextmanager.

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).





More information about the Tutor mailing list