tweak link
[dygraphs.git] / docs / ssi_server.py
... / ...
CommitLineData
1#!/usr/bin/python
2'''
3Use this in the same way as Python's SimpleHTTPServer:
4
5 ./ssi_server.py [port]
6
7The only difference is that, for files ending in '.html', ssi_server will
8inline SSI (Server Side Includes) of the form:
9
10 <!-- #include virtual="fragment.html" -->
11
12Run ./ssi_server.py in this directory and visit localhost:8000 for an exmaple.
13'''
14
15import os
16import ssi
17from SimpleHTTPServer import SimpleHTTPRequestHandler
18import SimpleHTTPServer
19import tempfile
20
21
22class SSIRequestHandler(SimpleHTTPRequestHandler):
23 """Adds minimal support for <!-- #include --> directives.
24
25 The key bit is translate_path, which intercepts requests and serves them
26 using a temporary file which inlines the #includes.
27 """
28
29 def __init__(self, request, client_address, server):
30 self.temp_files = []
31 SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
32
33 def do_GET(self):
34 SimpleHTTPRequestHandler.do_GET(self)
35 self.delete_temp_files()
36
37 def do_HEAD(self):
38 SimpleHTTPRequestHandler.do_HEAD(self)
39 self.delete_temp_files()
40
41 def translate_path(self, path):
42 fs_path = SimpleHTTPRequestHandler.translate_path(self, path)
43 if self.path.endswith('/'):
44 for index in "index.html", "index.htm":
45 index = os.path.join(fs_path, index)
46 if os.path.exists(index):
47 fs_path = index
48 break
49
50 if fs_path.endswith('.html'):
51 content = ssi.InlineIncludes(fs_path)
52 fs_path = self.create_temp_file(fs_path, content)
53 return fs_path
54
55 def delete_temp_files(self):
56 for temp_file in self.temp_files:
57 os.remove(temp_file)
58
59 def create_temp_file(self, original_path, content):
60 _, ext = os.path.splitext(original_path)
61 fd, path = tempfile.mkstemp(suffix=ext)
62 os.write(fd, content)
63 os.close(fd)
64
65 self.temp_files.append(path)
66 return path
67
68
69if __name__ == '__main__':
70 SimpleHTTPServer.test(HandlerClass=SSIRequestHandler)