Search code examples
pythonpython-3.xhttpserverhttpserver

Read HTTP request data in Python 3?


I am trying to write a basic "echo" HTTP server that writes back the raw data it receives in the request. How can I get the request data as a string?

This is my program:

#!/usr/bin/env python
from http.server import HTTPServer, BaseHTTPRequestHandler


class RequestHandler(BaseHTTPRequestHandler):
  def do_GET(self):
    print('data', self.rfile.readall())
    self.send_response(200)
    self.send_header('Content-Type', 'text/html')
    self.end_headers()
    message = 'Hello Client!'
    self.wfile.write(bytes(message, 'utf8'))
    return

def server_start():
  address = ('', 1992)
  httpd = HTTPServer(address, RequestHandler)
  httpd.serve_forever()


server_start()

Error:

self.rfile.readall(): '_io.BufferedReader' object has no attribute 'readall'

Solution

  • If it's a get request there won't be a body, so the data is going to be sent in the url.

    from http.server import HTTPServer, BaseHTTPRequestHandler
    import urlparse
    
    class RequestHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            parsed_path = urlparse.urlparse(self.path)
            print(parsed_path.query)
            ...
    

    Otherwise, you should implement a POST method if you want to send any more complex object as data (take a look at different HTTP methods if you're not familiar with them).

    A post method would be something like:

    def do_POST(self):
        post_body = self.rfile.readall()
    

    Note that here you can use the method rfile.readall(). Here you have a nice gist with some examples!