Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from http.server import BaseHTTPRequestHandler, HTTPServer
- from io import BytesIO
- from PIL import Image
- import socketserver
- class RequestHandler(BaseHTTPRequestHandler):
- get_request_count = 0
- def do_HEAD(self):
- self.send_response(200)
- self.end_headers()
- def do_GET(self):
- RequestHandler.get_request_count += 1
- if RequestHandler.get_request_count == 1:
- # Send a fake image on the first GET request
- self.send_fake_image()
- elif RequestHandler.get_request_count >= 2:
- # Redirect to localhost:8888 on the second GET request
- self.send_redirect()
- def send_fake_image(self):
- # Create a simple 1x1 pixel red image
- with BytesIO() as img_io:
- img = Image.new('RGB', (1, 1), (255, 0, 0))
- img.save(img_io, 'PNG')
- img_io.seek(0)
- self.send_response(200)
- self.send_header('Content-type', 'image/png')
- self.end_headers()
- self.wfile.write(img_io.read())
- def send_redirect(self):
- self.send_response(301)
- self.send_header('Location', 'http://localhost:8888')
- self.end_headers()
- def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000):
- server_address = ('', port)
- httpd = server_class(server_address, handler_class)
- print(f"Starting httpd on port {port}...")
- httpd.serve_forever()
- if __name__ == "__main__":
- run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement