3 from __future__
import print_function
8 if sys
.version_info
[0] > 2:
9 from urllib
import parse
as urlparse
# Python 3
10 from http
import server
14 import BaseHTTPServer
as server
15 import cPickle
as pickle
20 def __init__(self
, path
):
27 return "404 on " + self
.path
29 class MyHandler(server
.BaseHTTPRequestHandler
):
31 parsed
= urlparse
.urlparse(self
.path
)
34 if parsed
.path
.startswith('/redirect/'):
35 self
.send_response(302)
36 self
.wfile
.write(('Location: /' + parsed
.path
[1:].split('/', 1)[1]).encode('utf-8'))
39 leaf
= os
.path
.basename(parsed
.path
)
41 acceptable
= dict([(str(x
), x
) for x
in next_step
])
43 resp
= acceptable
.get(parsed
.path
, None) or \
44 acceptable
.get(leaf
, None) or \
45 acceptable
.get('*', None)
47 # (don't use a symlink as they don't work on Windows)
48 if leaf
== 'latest.xml':
50 elif parsed
.path
== '/0mirror/archive/http%3A%23%23example.com%3A8000%23HelloWorld.tgz':
51 leaf
= 'HelloWorld.tgz'
52 elif parsed
.path
== '/0mirror/feeds/http/example.com:8000/Hello.xml/impl/sha1=3ce644dc725f1d21cfcf02562c76f375944b266a':
53 leaf
= 'HelloWorld.tar.bz2'
56 self
.send_error(404, "Expected %s; got %s" % (next_step
, parsed
.path
))
57 elif parsed
.path
.startswith('/key-info/'):
58 self
.send_response(200)
60 self
.wfile
.write(b
'<key-lookup><item vote="good">Approved for testing</item></key-lookup>')
62 elif os
.path
.exists(leaf
) and not isinstance(resp
, Give404
):
63 self
.send_response(200)
65 with
open(leaf
, 'rb') as stream
:
66 self
.wfile
.write(stream
.read())
69 self
.send_error(404, "Missing: %s" % leaf
)
71 def handle_requests(*script
):
72 from subprocess
import Popen
, PIPE
74 # Pass the script on the command line as a pickle.
76 [sys
.executable
, __file__
, repr(pickle
.dumps(script
)) ],
77 stdout
=PIPE
, universal_newlines
=True)
79 # Make sure the server is actually running before we try to
81 l
= child
.stdout
.readline()
82 assert l
== 'Waiting for request\n', l
86 # Grab the script that was passed on the command line from the parent
87 script
= pickle
.loads(eval(sys
.argv
[1]))
88 server_address
= ('localhost', 8000)
89 httpd
= server
.HTTPServer(server_address
, MyHandler
)
91 sys
.stderr
= sys
.stdout
92 #sys.stdout = sys.stderr
93 print("Waiting for request")
94 sys
.stdout
.flush() # Make sure the "Waiting..." message is seen by the parent
96 for next_step
in script
:
97 if type(next_step
) != tuple: next_step
= (next_step
,)
99 httpd
.handle_request()
103 traceback
.print_exc()
106 if __name__
== '__main__':
107 # This is the child process. We have to import ourself and
108 # run the main routine there, or the pickled Give404 instances
109 # passed from the parent won't be recognized as having the
110 # same class (server.Give404).