return a text response from a http server in python

Here's an example of how to return a text response from a HTTP server in Python:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer

# HTTPRequestHandler class
class HTTPRequestHandler(BaseHTTPRequestHandler):
    
    # GET
    def do_GET(self):
        # Send response code
        self.send_response(200)

        # Send headers
        self.send_header('Content-type','text/plain; charset=utf-8')
        self.end_headers()

        # Send message back to client
        message = "Hello, world!"
        # Write content as utf-8 data
        self.wfile.write(bytes(message, "utf8"))
        return

# Create an HTTP server on port 8080
def run():
    print('Starting server...')
    
    server_address = ('', 8080)
    httpd = HTTPServer(server_address, HTTPRequestHandler)
    print('Server running on port 8080')
    httpd.serve_forever()


run()
782 chars
32 lines

In this example, the do_GET() method is used to handle incoming GET requests. It sends a response code of 200 and sets the content type to text/plain. It also sends a message back to the client in the form of a string, which is converted to UTF-8 bytes before being written to the server's output stream.

This code will create a HTTP server that listens on port 8080 and returns a "Hello, world!" message to any GET requests. You can modify the message to return any text response you want.

gistlibby LogSnag