h2non / filetype.py

Small, dependency-free, fast Python package to infer binary file types checking the magic numbers signature
https://h2non.github.io/filetype.py
MIT License
647 stars 109 forks source link

AttributeError while guessing image's kind #62

Open DensetsuNo opened 4 years ago

DensetsuNo commented 4 years ago
>>> import filetype
>>> import requests
>>> url = "https://45.img.avito.st/image/1/lCc6lra4OM5MM8rIHszqVLE1PsiYNTjI_1Y-woo1OM7K"
>>> r = requests.get(url)
>>> filetype.guess(r.content[:10])
<filetype.types.image.Jpeg object at 0x10b209f70>
>>> filetype.guess(r.content[:10]).kind
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Jpeg' object has no attribute 'kind'

From the initial response it would appear that the kind has been detected but once we call the method we have an AttributeError.

Python 3.8.0

h2non commented 4 years ago

You are reusing a readable stream that has been already read for the first 10 bytes.

The requests package response.content implements an iterable stream that flushes the internal buffer once data is pulled from it (in this case via iterable).

This should work instead:

import filetype
import requests
url = "https://45.img.avito.st/image/1/lCc6lra4OM5MM8rIHszqVLE1PsiYNTjI_1Y-woo1OM7K"
r = requests.get(url)
head = r.content[:10]
filetype.guess(head).kind
filetype.guess(head).kind
dbowes-fm commented 1 year ago

I know this is old, but I am in the same situation. This is what I have...

img_stream = requests.get(url, stream=True)
head = img_stream.content[:10]  # this has binary and JFIF for my test file
file_info = filetype.guess(head).kind

and I get the same error as OP. With your example you left out Stream, but I don't want to download the file locally. I am saving it to S3 directly.

Alisa-lisa commented 3 months ago

Hello from 2024. Same problem on local file:

file_info = filetype.guess(head)
print(file_info.extention)

results in:

AttributeError: 'Jpeg' object has no attribute 'extention'

Not sure why it breaks on this type