0

I have this code

httpd = HTTPServer(('127.0.0.1', 8000),SimpleHTTPRequestHandler)
httpd.handle_request()

httpd.handle_request() serves one request and then kills the server like intended. I want to capture this request as a variable so I can parse it later on. Something like

Request_Variable = httpd.handle_request()

*This code above doesn't work. But I'm looking for something similar Thanks

1 Answers1

1

You could extend the BaseHTTPRequestHandler and implement your own do_GET (resp. do_POST) method which is called when the server receives a GET (resp. POST) request.

Check out the documentation to see what instance variables a BaseHTTPRequestHandler object you can use. The variables path, headers, rfile and wfile may be of your interest.

from http.server import BaseHTTPRequestHandler, HTTPServer

class MyRequestHandler(BaseHTTPRequestHandler):
  def do_GET(self):
    print(self.path)
  def do_POST(self):
    content_length = int(self.headers.get('Content-Length'))
    print(self.rfile.read(content_length))

httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler)
httpd.handle_request()
# make your GET/POST request
Eri
  • 48
  • 5
  • Thank you so much. I ended up adding a few lines in this and now it works just fine. ```class MyRequestHandler(BaseHTTPRequestHandler): request = "" def do_GET(self): # print(self.path) MyRequestHandler.request = self.path def do_POST(self): content_length = int(self.headers.get('Content-Length')) print(self.rfile.read(content_length)) httpd = HTTPServer(('127.0.0.1', 8000), MyRequestHandler) httpd.handle_request() print("\n\n", MyRequestHandler.request)``` – Stathis Kapnidis Nov 13 '21 at 23:06