0

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'

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

1 Comment

The gist works great! I was trying to read a known length of bytes like self.rfile.read(5) in do_GET() but it just stuck. It appears do_GET() doesn't support any read. I tried self.rfile.readall() in do_POST() and it didn't work, same error as above. Thanks for the Content-Length method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.