open an html string in a browser?
piter
tojopiter at yahoo.com
Sat Jan 18 19:12:51 EST 2003
Hi,
I already did it.
I created it during learning Java and since Java documentation as a zip file
was ~20MB but unpacked more than 110 MB i decided to write that simple http
server in order to preserve my precious disk space ;-)
To my suprise it worked quite fast (even with frames, gifs and all this
stuff)
-------- CODE STARTS --------
'''
# The zip file http server
# example URL:
# http://localhost:8000/d:/java/doc/j2sdk-131-docs.zip/docs/guide/index.html
# where:
# - http://localhost:8000 - points to host where this script is running
# - d:/java/doc/j2sdk-131-docs.zip - points to zip file
# - docs/guide/index.html - points to file to display
#
# you can also skip file to display:
# http://localhost:8000/d:/java/doc/j2sdk-131-docs.zip/
# and in this case you can browse entire zip file
#
# or you can browse your entire filesystem:
# http://localhost:8000/d:/
# but I am pretty sure there are much *BETTER* ways of doinig it...
#
'''
import base64, BaseHTTPServer, SimpleHTTPServer, os, os.path, re, socket,
sys, urllib, zipfile
PORT = 8000
class zipHTTPRequestHandler( SimpleHTTPServer.SimpleHTTPRequestHandler ):
def listDir( self, dir, namelist ):
dirLen = len( dir )
dirs, files = {}, {}
for name in namelist:
if name.startswith( dir ):
paths = name[dirLen:].split( '/' )
if len( paths ) > 1:
dirs[paths[0]] = 1
elif paths[0] != '':
files[paths[0]] = 1
dirs[ '..' ] = 1
dirs = dirs.keys()
dirs.sort()
files = files.keys()
files.sort()
return dirs, files
def sendOK( self ):
self.send_response( 200, 'OK' )
self.end_headers()
def printDir( self, path, dirs, files ):
self.sendOK()
self.wfile.write( '''<html>
<head>
<style TYPE="text/css">
<!--
a {text-decoration: none}
.a1:hover {background-color: darkRed; color: white}
.a2:hover {background-color: darkBlue; color: white}
h2 {padding: 4pt; background-color: darkBlue; color: white}
b.darkBlue {color: darkBlue}
-->
</style>
</head>
<body>
''' )
self.wfile.write( '<h2>Zip file browser</h2>\n' )
for file in ['index.html', 'index.htm']:
if file in files:
self.wfile.write( 'Found <a class=a1 href="%s">  %s
 </a> in this directory<br>\n' % (file, file) )
self.wfile.write( '<p>\nIndex of [<b
class=darkBlue>%s</b>]</p>\n<table>\n' % path )
for dir in dirs:
self.wfile.write( ' <tr><td><img src="/icon::dir.gif"
align=top> <a class=a2 href="%s/">  %s  </a></td></tr>\n' %
(dir, dir) )
for file in files:
if file.endswith( '.zip' ):
icon = 'zip'
suffix = '/'
elif file.endswith( '.html' ) or file.endswith( '.htm' ):
icon = 'html'
suffix = ''
else:
icon = 'file'
suffix = ''
self.wfile.write( ' <tr><td><img src="/icon::%s.gif"
align=top> <a class=a2 href="%s%s">  %s  </a></td></tr>\n' %
(icon, file, suffix, file) )
self.wfile.write( '</table>\n\n</body>\n</html>' )
def do_GET( self ):
self.path = urllib.unquote_plus( self.path )
if self.path in ['/icon::dir.gif', '/icon::file.gif',
'/icon::zip.gif', '/icon::html.gif']:
# OK this is quite easy...
self.sendOK()
self.wfile.write( self.icons[self.path] )
return
if sys.platform.startswith( 'win' ):
path = self.path[1:] # for windoze remove the leading slash
else:
path = self.path # else: (eunuch) everything is OK
r = re.match( '(.*\.zip)/(.*)', path )
if r:
# yes, yes, yes! we have zip file!
file = r.group( 1 )
path = r.group( 2 )
try:
zf = self.zFile[file]
except KeyError:
try:
zf = self.zFile[file] = zipfile.ZipFile( file, 'r' )
except:
self.send_error( 404, 'Cannot open zip file [%s]' %
file )
if path == '' or path.endswith( '/' ):
# request is directory in zip file
dirs, files = self.listDir( path, zf.namelist() )
self.printDir( '%s::%s' % (file, path), dirs, files )
else:
# request is normal file in zip file
try:
data = zf.read( path )
self.sendOK()
self.wfile.write( data )
except:
self.send_error( 404, 'Cannot open [%s::%s]' % (file,
path) )
else:
# ordinary file/dir
if os.path.isdir( path ):
if path[-1] != '/':
self.send_response( 301, 'Moved Permanently' )
self.send_header( 'Location', self.path + '/' )
self.end_headers()
return
try:
list = os.listdir( path )
except OSError, s:
self.send_error( 403, 'Forbidden: %s' % s )
return
dirs = []
files = []
for item in list:
if os.path.isdir( path + '/' + item ):
dirs += [ item ]
else:
files += [ item ]
if os.path.normpath( os.path.join(path, '..') ) != path:
dirs += [ '..' ]
dirs.sort()
files.sort()
self.printDir( path, dirs, files )
elif os.path.isfile( path ):
self.sendOK()
self.wfile.write( open(path).read() )
else:
self.send_error( 404, 'File [%s] not found' % path )
print __doc__
zipHTTPRequestHandler.zFile = {}
zipHTTPRequestHandler.icons = {}
zipHTTPRequestHandler.icons['/icon::dir.gif'] = base64.decodestring( '''\
R0lGODlhEAAQAPUpAAAAABoaGikpKTk5OQA8WkVFRVhYWGlpaXR0dAtVhA5ekQhnmQdxoxBtoBF3
qBJ/sShsjSdokgeGtROAshaayxmv7jiixTy57VenxlawzV2x0HS71J2dnYaltKioqLi4uILD2JHJ
28G+vsfHx9nY2MHh7dPt9ujo6Pb29gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEBACkALAAAAAAQABAAAAbmwFQq
lQIUUqlUKpVKpVKpVCoVGJ0KhUEqlUqlUqlUarAgIDyjUwFQQABSqVRKUDJtFgSEZ3Q6nYCAVCoV
uFg2JROIQUB4RqdCKiWoSCyaDahkAjEICEMqFaA0HhKJJbMJlUybQSolmCQUi8ZDIrEAMZtSIZUq
oE4dSEKxcDgkkk0hlSqgUKcTqQNJKBYNzCCVKpxOpxOJRBp1IInIIJUajEgkEmk0Ao5EIhGikEql
AIODaDQaiUSfz6GQSqVSqRRgYPh8Ph7PoZBKpVKpVCqVAggMHM9hkEqlUqlUKgVMpVIpgGCQCgIA
Ow==
''' )
zipHTTPRequestHandler.icons['/icon::file.gif'] = base64.decodestring( '''\
R0lGODlhEAAQAPUiAAAAADAwMEJCQlhYWGxsbHBwcI6DcpGJfLyec7yie4yJhpONg5WSjJqZmb2o
h7ytlL62r7y3scCvkcKzmsO6p8bBtuXMp+jUts7Ozt7e3uzdxe7gyeji2fHm1urq6vTt4vfy6/39
/QAAAAAAAAAAAAAAAAAAAAAAAAAAA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UI4
A2EUWF9TTjIdGAYgV19aQgMUJFheTzYeIhgJBEpdXIBHAwcuJ1A6PCwhGAkEQl5aRwMHKS4oNh4e
HxYFBEFaWEcDYRQsLSo2MQ8GBBJBWFg/A2EEHhocMS8MBAQvSlhUPwNhYQQGFA4NCAUvQElUUjQD
YWFhYQQEBA86QElSVFE0A2FhYWEPSkFBSUhHPz8zMwNhYWFhDwMDAwMDAwMGgAMDAwOBADs=
''' )
httpd = BaseHTTPServer.HTTPServer( ('', PORT), zipHTTPRequestHandler )
urlInfo = ( socket.gethostname(), PORT )
print 'Host [%s] started listening on port [%d]' % urlInfo
print 'Try e.g. http://%s:%d/pathToYourFile(s)' % urlInfo
httpd.serve_forever()
-------- CODE ENDS --------
Piter
U¿ytkownik "Dennis Reinhardt" <DennisR at dair.com> napisa³ w wiadomo¶ci
news:sXjW9.126$lE7.20810881 at newssvr17.news.prodigy.com...
> > The reason is that zipfile.read('myfile.html') returns a string,
> containing
> > the contents of the file. However, Webbrowser requires a URL (in this
case
> > the name of an html file).
>
> You *could* implement a very simple http server. the server returns the
> string when requested by browser. The following command (among others)
> launches browser:
> os.startfile("http://localhost")
>
> You would need port 80 open locally or attach to some other port and
> identify same in URL..
> --
>
> Dennis Reinhardt
>
> http://www.dair.com
>
>
More information about the Python-list
mailing list