Skip to content
Advertisement

How to print fp in HTTPError?

After seeing this error with my urlopen() function:

JavaScript

I wrote a catch exception, but fp is empty when I printed it out. Any ideas?

JavaScript

Output:

JavaScript

fp isn’t empty in the HTTPError class

JavaScript

Output:

JavaScript

Thanks.

Advertisement

Answer

Perhaps I’m dense; but a few items that might help you.

  1. You have an errant " in your print("str(fp)). (Thanks to @CrazyChucky for pointing that out. Was particularly stupid of me to miss that. Made more sense without the ")

  2. In your code:

JavaScript

I noticed you do a print (fp.readlines()) and then raise the error. After that print (fp.readlines()), the filepointer will be at the end of the file. So any further fp.readlines() will return []

I’d suggest the following:

JavaScript

After noticing that the OP got an error with the fp.seek(0), and noticing that fp is a HTTPResponse object, I’m not sure it’s even possible to do an analogous seek() action as the internal fp of HTTPResponse is a socket file which (iiuc), doesn’t allow seeking.

With that said, and if someone smarter than me can correct me, the options are:

  1. Remove the fp.readlines() altogether as that will set the fp pointer to the end and you can’t reset it.

  2. Copy the fp.readlines() items to a new file object (BytesIO()) and pass that to HTTPError.

i.e.

JavaScript

A possible problem that I see is if HTTPError requires new_fp to be a HTTPResponse object. But since this is a RAISE line, the script/program would stop (assuming here..).

This is what I believe will give you what you want, though I’m doubtful it is 100% what you want. I apologize.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement