Advertisement
Guest User

example

a guest
Nov 1st, 2023
1,367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | Source Code | 0 0
  1. from http.server import BaseHTTPRequestHandler, HTTPServer
  2. from io import BytesIO
  3. from PIL import Image
  4. import socketserver
  5.  
  6. class RequestHandler(BaseHTTPRequestHandler):
  7.     get_request_count = 0
  8.  
  9.     def do_HEAD(self):
  10.         self.send_response(200)
  11.         self.end_headers()
  12.  
  13.     def do_GET(self):
  14.         RequestHandler.get_request_count += 1
  15.  
  16.         if RequestHandler.get_request_count == 1:
  17.             # Send a fake image on the first GET request
  18.             self.send_fake_image()
  19.         elif RequestHandler.get_request_count >= 2:
  20.             # Redirect to localhost:8888 on the second GET request
  21.             self.send_redirect()
  22.  
  23.     def send_fake_image(self):
  24.         # Create a simple 1x1 pixel red image
  25.         with BytesIO() as img_io:
  26.             img = Image.new('RGB', (1, 1), (255, 0, 0))
  27.             img.save(img_io, 'PNG')
  28.             img_io.seek(0)
  29.             self.send_response(200)
  30.             self.send_header('Content-type', 'image/png')
  31.             self.end_headers()
  32.             self.wfile.write(img_io.read())
  33.  
  34.     def send_redirect(self):
  35.         self.send_response(301)
  36.         self.send_header('Location', 'http://localhost:8888')
  37.         self.end_headers()
  38.  
  39.  
  40. def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000):
  41.     server_address = ('', port)
  42.     httpd = server_class(server_address, handler_class)
  43.     print(f"Starting httpd on port {port}...")
  44.     httpd.serve_forever()
  45.  
  46.  
  47. if __name__ == "__main__":
  48.     run()
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement