2012-11-02 2 views
4

python-requests와 python-magic을 사용하여 모든 내용을 가져 오지 않고 웹 자원의 MIME 유형을 테스트하고 싶습니다 (특히이 자원 예 : ogg 파일 또는 PDF 파일). 결과에 따라, 나는 그것을 전부 가져 오기로 결정할지도 모른다. 그러나 MIME 형식을 테스트 한 후에 텍스트 메서드를 호출하면 아직 소비되지 않은 내용 만 반환됩니다. 응답 내용을 사용하지 않고 MIME 형식을 테스트하려면 어떻게해야합니까?python-requests : 응답 내용을 모두 소비하지 않고 머리 부분을 가져 오는 것

아래는 현재 코드입니다.

import requests 
import magic 


r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False) 
mime = magic.from_buffer(r.iter_content(256).next(), mime=True) 

if mime == "text/html": 
    print(r.text) # I'd like r.text to give me the entire response content 

감사!

답변

4

참고 :이 질문을받은 시점에서 머리글 만 가져 오는 올바른 방법은 prefetch=False입니다. 이 옵션의 이름이 stream으로 바뀌고 부울 값이 반전되므로 stream=True이 필요합니다.

원래 답변은 다음과 같습니다.


iter_content()을 사용한 후에는 계속 사용해야합니다. .text은 간접적으로 후드 아래에서 동일한 인터페이스를 사용합니다 (.content 통해). 파이썬은 3

대안은이 개 요청을하는 것입니다 사용 추정

from requests.compat import chardet 

r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False) 
peek = r.iter_content(256).next() 
mime = magic.from_buffer(peek, mime=True) 

if mime == "text/html": 
    contents = peek + b''.join(r.iter_content(10 * 1024)) 
    encoding = r.encoding 
    if encoding is None: 
     # detect encoding 
     encoding = chardet.detect(contents)['encoding'] 
    try: 
     textcontent = str(contents, encoding, errors='replace') 
    except (LookupError, TypeError): 
     textcontent = str(contents, errors='replace') 
    print(textcontent) 

: 모든 iter_content()를 사용하여, 당신은 일 .text을해야 즉

는 손으로 수행합니다

r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False) 
mime = magic.from_buffer(r.iter_content(256).next(), mime=True) 

if mime == "text/html": 
    print(r.requests.get("http://www.december.com/html/demo/hello.html").text) 

파이썬 2 버전 :

r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False) 
peek = r.iter_content(256).next() 
mime = magic.from_buffer(peek, mime=True) 

if mime == "text/html": 
    contents = peek + ''.join(r.iter_content(10 * 1024)) 
    encoding = r.encoding 
    if encoding is None: 
     # detect encoding 
     encoding = chardet.detect(contents)['encoding'] 
    try: 
     textcontent = unicode(contents, encoding, errors='replace') 
    except (LookupError, TypeError): 
     textcontent = unicode(contents, errors='replace') 
    print(textcontent) 
+0

감사합니다. – user1415785

+0

안녕하세요, 첫 번째 솔루션을 작동시킬 수 없습니다. "self"에 대한 참조를 "r"로 대체 한 후 "RuntimeError :이 응답의 콘텐츠가 이미 소비되었습니다"라는 오류 메시지가 나타납니다. 어떤 생각? 감사! – user1415785

+0

@ user1415785 : 죄송합니다. 내 실수입니다. 'self.content'를'contents'로 대체했습니다. 이것은'.text' 소스로부터 좀 더 직접적인 번역입니다. –

7

'content-type'으로 충분하면 'Get'대신 HTTP 'Head'요청을 발행하여 HTTP 헤더를 수신 할 수 있습니다.

import requests 

url = 'http://www.december.com/html/demo/hello.html' 
response = requests.head(url) 
print response.headers['content-type'] 
+0

감사합니다. 사실 그것은 더 쉬울 것이지만, 선언 된 content-type이 잘못된 경우에는 python-magic을 사용하여 두 번째 의견을 제시하고 싶습니다. – user1415785