2012-06-29 3 views
5

URL이 유효한 이미지가 장고에 링크되어 있는지 여부를 확인할 수있는 방법이 있는지 궁금합니다.Django : 특정 URL에 이미지가 있는지 확인하십시오.

+1

machine을 Django로 만들면 파일을 읽고 검증 할 수 있습니다. 그렇지 않으면 REST 호출을 작성하고 결과를 구문 분석해야합니다. – freakish

+0

이미지가 Django와 동일한 컴퓨터에 존재하지 않습니다. 실제로 사용자가 일부 이미지의 URL을 제출해야하는 양식이 있습니다. URL이 실제 이미지에 링크되어 있는지 확인하고 싶습니다. –

+0

읽어보기 : http://stackoverflow.com/questions/7699796/how-do-you-get-django-to-make-a-restful-call (중복 가능). – freakish

답변

3

다음은 오류 방지 방법입니다. 먼저 URL을 구문 분석하여 도메인과 나머지 도메인을 가져옵니다.

>>> from urllib.parse import urlparse 
>>> url = 'http://example.com/random/folder/path.html' 
>>> parse_object = urlparse(url) 
>>> parse_object.netloc 
'example.com' 
>>> parse_object.path 
'/random/folder/path.html' 
>>> parse_object.scheme 
'http' 

이제 위의 정보를 사용하여 콘텐츠 형식을 가져옵니다. sstatic.net 대신 parse_object.netloc을 사용하고 하드 코드 된 경로 대신 parse_object.path을 사용하십시오.

>>> import httplib 
>>> conn = httplib.HTTPConnection("sstatic.net") 
>>> conn.request("HEAD", "/stackoverflow/img/favicon.ico") 
>>> res = conn.getresponse() 
>>> print res.getheaders() 
[('content-length', '1150'), ('x-powered-by', 'ASP.NET'), ('accept-ranges', 'bytes'),   ('last-modified', 'Mon, 02 Aug 2010 06:04:04 GMT'), ('etag', '"2187d82832cb1:0"'), ('cache-control', 'max-age=604800'), ('date', 'Sun, 12 Sep 2010 13:39:26 GMT'), ('content-type', 'image/x-icon')] 

1150 바이트의 이미지 (이미지/* mime-type)입니다. 전체 리소스를 가져올 것인지 결정할 수있는 충분한 정보.

편집 단축 URL에 대한

, 당신이 얻을 응답에서, http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg를 가리키는 http://goo.gl/IwruD처럼 'location'라는 추가 매개 변수가있다.

여기에 내가 무슨 말입니다 :

>>> import httplib 
>>> conn = httplib.HTTPConnection("goo.gl") 
>>> conn.request("HEAD", "/IwruD") 
>>> res = conn.getresponse() 
>>> print res.getheaders() 
[('x-xss-protection', '1; mode=block'), 
('x-content-type-options', 'nosniff'), 
('transfer-encoding', 'chunked'), 
('age', '64'), 
('expires', 'Mon, 01 Jan 1990 00:00:00 GMT'), 
('server', 'GSE'), 
('location', 'http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg'), 
('pragma', 'no-cache'), 
('cache-control', 'no-cache, no-store, max-age=0, must-revalidate'), 
('date', 'Sat, 30 Jun 2012 08:52:15 GMT'), 
('x-frame-options', 'SAMEORIGIN'), 
('content-type', 'text/html; charset=UTF-8')] 

가 직접 URL에있는 동안, 당신은 그것을 찾을 것입니다.

>>> import httplib 
>>> conn = httplib.HTTPConnection("ubuntu.icafebusiness.com") 
>>> conn.request("HEAD", "/images/ubuntugui2.jpg") 
>>> res = conn.getresponse() 
>>> print res.getheaders() 
[('content-length', '78603'), ('accept-ranges', 'bytes'), ('server', 'Apache'), ('last-modified', 'Sat, 16 Aug 2008 01:36:17 GMT'), ('etag', '"1fb8277-1330b-45489c3ad2640"'), ('date', 'Sat, 30 Jun 2012 08:55:46 GMT'), ('content-type', 'image/jpeg')] 

당신은 그 사용하여 간단한 코드를 볼 수 있습니다

>>> r = res.getheaders() 
>>> redirected = False 
>>> for e in r: 
>>>  if(e[0] == 'location'): 
>>>   redirected = e 
>>> 
>>> if(redirected != False): 
>>>  print redirected[1] 
'http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg' 
+0

파이썬 인터프리터가 "ImportError : No parse named 모듈"이라고 말합니다 .1 단계에서 메서드가 실패했습니다. 모든 아이디어? –

+0

파이썬 3을 사용하고 있습니다. 아직 파이썬 2.7을 사용하고 있습니다. –

+0

또 하나 의심의 여지가 있습니다. 'http://ubuntu.icafebusiness.com/images/ubuntugui2.jpg'가 URL이고, google url shortner가 이제 'http://goo.gl/IwruD'가됩니다.이 단축 URL에서 귀하의 방법이 작동하지 않는 경우, "ResponseNotReady"라고 표시됩니다. –

3

urllib2을 사용하여이를 간단히 확인할 수 있습니다.

>>> import urllib2 
>>> url = 'https://www.google.com.pk/images/srpr/logo3w.png' 
>>> try: 
... f = urllib2.urlopen(urllib2.Request(url)) 
... imageFound = True 
... except: 
... imageFound = False 
... 
>>> imageFound 
True 
4

실제로 유효한 이미지 중인지 확인하기 위해 requestsPIL 사용 : 이미지가 동일에있는 경우

>>> import requests 
>>> from PIL import Image 
>>> from StringIO import StringIO 
>>> r = requests.get('http://cdn.sstatic.net/stackoverflow/img/sprites.png') 
>>> im = Image.open(StringIO(r.content)) 
>>> im 
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=238x1073 at 0x2845EA8> 
+0

이미지가 없으면 어떻게 될까요? 코드가 충돌하거나 메신저의 일부 속성을 확인해야합니까? 부울을 반환하는 함수로 코드를 업데이트 할 수 있습니까? – Radu

+0

'r.status_code'는 200이되지 않습니다 – jterrace

+0

HTTP 상태 코드를 제외하고 Image.open은 내가 생각하고있는 어떤 종류의 오류를 던져야합니까? PIL은 이것에별로 도움이되지 않습니다 ... 저는 또한 http://effbot.org/imagingbook/image.htm#tag-Image.Image.verify를보고 있었지만 사용할 내용을 알아 내지 못했습니다. – Radu

관련 문제