@@ -688,31 +688,41 @@ def send_head(self):
688688 self .send_error (HTTPStatus .NOT_FOUND , "File not found" )
689689 return None
690690
691- fs = os .fstat (f .fileno ())
692-
693691 try :
692+ fs = os .fstat (f .fileno ())
694693 # Use browser cache if possible
695694 if ("If-Modified-Since" in self .headers
696695 and "If-None-Match" not in self .headers ):
697696 # compare If-Modified-Since and time of last file modification
698- ims = email .utils .parsedate_to_datetime (
699- self .headers ["If-Modified-Since" ])
700- if (ims is not None and
701- ims .tzinfo is datetime .timezone .utc ):
702- # compare to UTC datetime of last modification
703- last_modif = datetime .datetime .fromtimestamp (fs .st_mtime ,
704- ims .tzinfo )
705- # remove microseconds, like in If-Modified-Since
706- last_modif = last_modif .replace (microsecond = 0 )
707- if last_modif <= ims :
708- self .send_response (HTTPStatus .NOT_MODIFIED )
709- self .end_headers ()
710- f .close ()
711- return
697+ try :
698+ ims = email .utils .parsedate_to_datetime (
699+ self .headers ["If-Modified-Since" ])
700+ except :
701+ # ignore ill-formed values
702+ ims = None
703+ if ims is not None :
704+ if ims .tzinfo is None :
705+ # obsolete format with no timezone, cf.
706+ # https://tools.ietf.org/html/rfc7231#section-7.1.1.1
707+ ims = ims .replace (tzinfo = datetime .timezone .utc )
708+ if ims .tzinfo is datetime .timezone .utc :
709+ # compare to UTC datetime of last modification
710+ last_modif = datetime .datetime .fromtimestamp (
711+ fs .st_mtime , datetime .timezone .utc )
712+ # remove microseconds, like in If-Modified-Since
713+ last_modif = last_modif .replace (microsecond = 0 )
714+
715+ if last_modif <= ims :
716+ self .send_response (HTTPStatus .NOT_MODIFIED )
717+ self .end_headers ()
718+ f .close ()
719+ return None
720+
712721 self .send_response (HTTPStatus .OK )
713722 self .send_header ("Content-type" , ctype )
714723 self .send_header ("Content-Length" , str (fs [6 ]))
715- self .send_header ("Last-Modified" , self .date_time_string (fs .st_mtime ))
724+ self .send_header ("Last-Modified" ,
725+ self .date_time_string (fs .st_mtime ))
716726 self .end_headers ()
717727 return f
718728 except :
0 commit comments