Back to index

python-weblib  1.3.9
httphelper.py
Go to the documentation of this file.
00001 """
00002 httphelper.py - basic HTTP-related functions
00003 (c) by Michael Stroeder <michael@stroeder.com>
00004 
00005 This module is distributed under the terms of the
00006 GPL (GNU GENERAL PUBLIC LICENSE) Version 2
00007 (see http://www.gnu.org/copyleft/gpl.html)
00008 
00009 $Id: httphelper.py,v 1.13 2010/10/27 08:27:10 michael Exp $
00010 """
00011 
00012 __version__ = '0.0.5'
00013 
00014 import sys,time
00015 
00016 HTTP_LINESEP = '\r\n'
00017 
00018 def DateTimeRFC1123(secs=0):
00019   """
00020   Return seconds as RFC1123 date/time format preferred
00021   for HTTP 1.1 (see RFC2616)
00022   """
00023   return time.strftime(
00024     '%a, %d %b %Y %H:%M:%S GMT',
00025     time.gmtime(secs)
00026   )
00027 
00028 # Write HTTP-Header
00029 def SendHeader(
00030   outf=sys.stdout,
00031   contenttype='text/html',
00032   charset='ISO-8859-1',
00033   contentlength=None,
00034   expires_offset=0,
00035   current_datetime=None,
00036   additional_header=None
00037 ):
00038   """
00039   Generate HTTP header
00040 
00041   outf
00042       File object used for sending to client.
00043   contenttype
00044       MIME type of object in HTTP body. Default is 'text/html'.
00045   charset
00046       Character set used. Default is 'ISO-8859-1'.
00047   contentlength
00048       Content-Length if known and gzip-encoding is not used.
00049       Default is None indicating unknown length.
00050   expires_offset=0,
00051       Expiry time from current time in seconds. Default is 0.
00052   current_datetime
00053       Last modification time in seconds.
00054       If zero (default) 'Last-modified' header will be omitted.
00055   additional_header
00056       Dictionary containing arbitrary additional HTTP header fields
00057       as key/value-pairs.
00058   """
00059   additional_header = additional_header or {}
00060   gzip = hasattr(outf,'fileobj')
00061   # Get current time as GMT (seconds since epoch)
00062   gmt = time.time()
00063   # Determine times for HTTP header
00064   if current_datetime is None:
00065     current_datetime = DateTimeRFC1123(gmt)
00066   expires = DateTimeRFC1123(gmt+expires_offset)
00067   # Build list of header lines
00068   header_lines = []
00069   # Write header
00070   if not (contenttype is None):
00071     if contenttype.lower().startswith('text/'):
00072       header_lines.append('Content-Type: %s;charset=%s' % (contenttype,charset))
00073     else:
00074       header_lines.append('Content-Type: %s' % (contenttype))
00075   if not (contentlength is None):
00076     header_lines.append('Content-Length: %d' % (contentlength))
00077   if gzip:
00078     header_lines.append('Content-Encoding: gzip')
00079     header_lines.append('Vary: Accept-Encoding')
00080   header_lines.append('Date: %s' % (current_datetime))
00081   header_lines.append('Last-Modified: %s' % (current_datetime))
00082   header_lines.append('Expires: %s' % (expires))
00083   for h,v in additional_header.items():
00084     header_lines.append('%s: %s' % (h,v))
00085   # Write empty end-of-header line
00086   header_lines.extend(['',''])
00087   if gzip:
00088     outf.fileobj.write(HTTP_LINESEP.join(header_lines))
00089     outf.fileobj.flush()
00090   else:
00091     outf.write(HTTP_LINESEP.join(header_lines))
00092   return
00093 
00094 
00095 def SimpleMsg(outf,msg):
00096   """
00097   Output HTML text.
00098   """
00099   SendHeader(outf)
00100   outf.write("""
00101 <html>
00102   <head>
00103     <title>Note</title>
00104   </head>
00105   <body>
00106     %s
00107   </body>
00108 </html>
00109     """ % (msg)
00110   )
00111 
00112 def URLRedirect(outf,url,refreshtime=0,msg='Redirecting...'):
00113   """
00114   Output HTML text with redirecting <head> section.
00115   """
00116   SendHeader(outf)
00117   outf.write("""
00118 <html>
00119   <head>
00120     <meta http-equiv="refresh" content="%d; url=%s">
00121   </head>
00122   <body>
00123     %s <a href="%s">Redirecting...</a>
00124   </body>
00125 </html>
00126     """ % (refreshtime,url,msg,url)
00127   )