Python 3 simple http server with GET functional

Viewed 89

I can't find any python code for the equiavalent of

python -m http.server port --bind addr --directory dir

So I need basicaly working server class that prcoess at least GET requests. Most of the things I found on google either http server with some special needs or something like that, where you need to code response behaviour be yourself:

from http.server import BaseHTTPRequestHandler, HTTPServer

def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

run()

All that I need is default working skeleton of python http server, where you can provide address, port and directory, and it would normally process GET reqeuests.

3 Answers

You need to subclass the BaseHTTPRequestHandler to, well, handle the requests:

class HTTPRequestHandler(BaseHTTPRequestHandler):
    """HTTP request handler with additional properties and functions."""

     def do_GET(self):
        """handle GET requests."""
        # Do stuff.

Why not use the requests library ?

import requests

#the required first parameter of the 'get' method is the 'url'(instead of get you can use any other http type, as needed):

r = requests.get('https://stackoverflow.com/questions/73089846/python-3-simple-http-get-functional')

#you can print many other things as well such as content, text and so on
print(r.status_code) 

Check the documentation https://requests.readthedocs.io/en/latest/

That's what I ended up with:

# python -m http.server 8000 --directory ./my_dir

from http.server import HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler
import os


class HTTPHandler(SimpleHTTPRequestHandler):
    """This handler uses server.base_path instead of always using os.getcwd()"""
    def translate_path(self, path):
        path = SimpleHTTPRequestHandler.translate_path(self, path)
        relpath = os.path.relpath(path, os.getcwd())
        fullpath = os.path.join(self.server.base_path, relpath)
        return fullpath


class HTTPServer(BaseHTTPServer):
    """The main server, you pass in base_path which is the path you want to serve requests from"""
    def __init__(self, base_path, server_address, RequestHandlerClass=HTTPHandler):
        self.base_path = base_path
        BaseHTTPServer.__init__(self, server_address, RequestHandlerClass)


web_dir = os.path.join(os.path.dirname(__file__), 'my_dir')
httpd = HTTPServer(web_dir, ("", 8000))
httpd.serve_forever()

Simple HTTP server that handles GET requests with, working with certain directory

Related