Ticket #7061: server.py

File server.py, 1.7 KB (added by dcf, 6 years ago)

Test server for img redirect technique.

Line 
1#!/usr/bin/env python
2
3import BaseHTTPServer
4import getopt
5import socket
6import sys
7
8ADDR = ["", 8080]
9
10def usage(f = sys.stdout):
11    print >> f, "Usage: %s [ADDRESS [PORT]]" % sys.argv[0]
12
13class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
14    def do_GET(self):
15        if self.path == "/":
16            self.send_response(200)
17            self.send_header("Content-type", "text/html; charset=utf-8")
18            self.end_headers()
19            print >> self.wfile, """\
20<!DOCTYPE html>
21<body bgcolor=dodgerblue>
22<img src="x.png" width=200 height=200>
23</body>
24"""
25            return
26        if self.path == "/x.png":
27            self.send_response(302)
28            self.send_header("Content-type", "image/png")
29            self.send_header("Location", "x.html")
30            self.end_headers()
31            return
32        if self.path == "/x.html":
33            self.send_response(200)
34            self.send_header("Content-type", "text/html; charset=utf-8")
35            self.end_headers()
36            print >> self.wfile, """\
37<!DOCTYPE html>
38<body bgcolor=slateblue>
39Inner HTML.
40</body>
41"""
42
43        self.send_response(404)
44        self.send_header("Content-type", "text/html; charset=utf-8")
45        self.end_headers()
46        print >> self.wfile, """\
47<!DOCTYPE html>
48Not found.
49"""
50
51class Server(BaseHTTPServer.HTTPServer):
52    allow_reuse_address = True
53
54opts, args = getopt.gnu_getopt(sys.argv[1:], "h", ["help"])
55for o, a in opts:
56    if o == "-h" or o == "--help":
57        usage()
58        sys.exit(0)
59
60if len(args) >= 1:
61    ADDR[0] = args[0]
62if len(args) >= 2:
63    ADDR[1] = args[1]
64if len(args) >= 3:
65    usage(sys.stderr)
66    os.exit(1)
67
68server = Server(tuple(ADDR), Handler)
69print "Listening on %s:%d." % (server.server_name, server.server_port)
70server.serve_forever()