Python HTTP server

Dolores 81 Published: 08/05/2024

Python HTTP server

Here's a detailed guide on setting up a Python HTTP server:

Python has several libraries that allow you to create an HTTP server without needing to install additional software or modules. One such library is http.server. This module is part of the Python Standard Library, which means it comes pre-installed with your Python interpreter.

To start the server, open a terminal and type the following command:

python -m http.server

This will launch a simple HTTP server on port 8000 by default. You can specify a different port number if you want to. For example, to run the server on port 8080, use this command:

python -m http.server 8080

Once the server is running, you can access it from your web browser by navigating to http://localhost:8000/ (or the port number you specified). You will see a directory listing of the current working directory.

You can also create a custom HTTP server using Python's built-in module, BaseHTTPRequestHandler, and the SocketServer module. This allows for more control over how your server handles requests and sends responses.

Here is an example of a basic server that responds to GET and POST requests:

from http.server import BaseHTTPRequestHandler, HTTPServer

import urllib.parse

class RequestHandler(BaseHTTPRequestHandler):

def do_GET(self):

self.send_response(200)

self.send_header('Content-type', 'text/plain')

self.end_headers()

self.wfile.write(b'Hello from Python!')

def do_POST(self):

query = self.rfile.read(int(self.headers.get('Content-Length'))).decode()

print(f'Received POST request with body: {query}')

self.send_response(200)

self.send_header('Content-type', 'text/plain')

self.end_headers()

self.wfile.write(b'POST request received!')

def run(server_class=HTTPServer, handler_class=RequestHandler, port=8081):

server_address = ('', port)

httpd = server_class(server_address, handler_class)

print(f'Starting httpd on port {port}...')

httpd.serve_forever()

if name == "main":

from sys import argv

if len(argv) > 1:

run(int(argv[1]))

else:

run()

To run this server, save it to a file (e.g., server.py), navigate to the directory containing the file in your terminal, and use the following command:

python server.py

This will start the server on port 8081 by default. You can access it from your web browser by navigating to http://localhost:8081/. The server responds to GET requests with a simple "Hello from Python!" message and POST requests with a confirmation message.

This is just a basic example of how you can create an HTTP server using Python. Depending on your specific needs, you may want to add additional features or handle different types of requests.

Python HTTP module

I'd be happy to help you with that!

The Python http module is a built-in library that provides functions for working with the Hypertext Transfer Protocol (HTTP). It allows you to send and receive data over the internet, making it an essential tool for building web applications or interacting with web services.

Here are some of the key features of the Python http module:

Sending HTTP Requests: The http module provides several functions for sending different types of HTTP requests, including: get(): Sends a GET request to a specified URL. post(): Sends a POST request to a specified URL with a specified payload (e.g., form data or JSON). put(): Sends a PUT request to a specified URL with a specified payload. delete(): Sends a DELETE request to a specified URL. Receiving HTTP Responses: After sending an HTTP request, the http module can be used to receive and parse the response from the server. The most commonly used function for this is: request(): Sends an HTTP request and returns the response as a requests.Response object. Working with Cookies: The http module provides functions for setting, getting, and deleting cookies. cookie_jar(): A dictionary-like object that stores cookies received from the server. set_cookie(): Sets a cookie on the client-side. get_cookie(): Retrieves a cookie from the client-side. Working with Headers: The http module provides functions for setting, getting, and deleting HTTP headers. headers(): A dictionary-like object that stores HTTP request and response headers. add_header(): Adds an HTTP header to the request or response. remove_header(): Removes an HTTP header from the request or response.

Here's a simple example of using the Python http module to send a GET request and receive the response:

import http.client
Create an instance of the http.client.HTTPConnection class

conn = http.client.HTTPConnection("www.example.com")

Send a GET request to the server

conn.request(method="GET", url="/path/to/resource")

Get the response from the server

response = conn.getresponse()

Print the response status code and reason phrase

print(response.status, response.reason)

Close the connection

conn.close()

And here's an example of using the Python http module to send a POST request with form data:

import http.client
Create an instance of the http.client.HTTPConnection class

conn = http.client.HTTPConnection("www.example.com")

Set the request method and URL

method = "POST"

url = "/path/to/resource"

Set the request headers

headers = {"Content-Type": "application/x-www-form-urlencoded"}

Set the form data to be sent in the request body

form_data = {"key1": "value1", "key2": "value2"}

Send the POST request with the form data

conn.request(method=method, url=url, headers=headers, body=form_data)

Get the response from the server

response = conn.getresponse()

Print the response status code and reason phrase

print(response.status, response.reason)

Close the connection

conn.close()

I hope this helps you get started with using the Python http module!