[Python-es] Cabecera html y respuesta 304

Gerardo Diez García gerardo.diez.garcia en gmail.com
Vie Dic 6 00:52:18 CET 2013


Hola, estoy haciendo un script tonto para descargar las actualizaciones
de un archivo en línea. Quiero andar comprobando si existen
modificaciones desde que modifiqué el archivo por última vez así que
trato de usar la cabecera If-Modified-Since. Lo curioso es que si tomo
como referencia el valor de ayer, me da el resultado esperado con un
código 304. Mientras que si empleo el valor tomado del archivo me da una
respuesta 200. El trozo de código afectado es este:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import datetime
import os

arch = "hosts"

(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(arch)
print datetime.datetime.fromtimestamp(atime).strftime("%a, %d %b %Y
%H:%M:%S GMT")
GoodFormated = datetime.datetime.fromtimestamp(atime).strftime("%a, %d
%b %Y %H:%M:%S GMT")


req = urllib2.Request('http://someonewhocares.org/hosts/hosts')
req.add_header('If-Modified-Since', GoodFormated)

print "Código %s" % urllib2.urlopen(req).code
resp = urllib2.urlopen(req)
LastMod = resp.info()['Last-Modified']
print "Ultima modificación %s" % datetime.datetime.strptime(LastMod,
"%a, %d %b %Y %H:%M:%S GMT")

AnotherDay = datetime.datetime.today() - datetime.timedelta(days=1)
AnotherGoodFormated = AnotherDay.strftime("%a, %d %b %Y %H:%M:%S GMT")
print AnotherGoodFormated

req = urllib2.Request('http://someonewhocares.org/hosts/hosts')
req.add_header('If-Modified-Since', AnotherGoodFormated)

try:
    urllib2.urlopen(req)
except urllib2.URLError, e:
    if e.code == 304:
        print "Aquí está. Código %s" % e.code

¿A alguien se le ocurre qué está pasando?
Muchas gracias


Más información sobre la lista de distribución Python-es