[Python] Quickly create a simple HTTP server (http.server)

insert image description here

introduction

http.serverIs socketserver.TCPServera subclass of that creates and listens on an HTTP socket and dispatches requests to handlers. http.serverThis article is a tutorial on how to quickly build a simple HTTP server using Python modules.

Install

Python3 built-in standard modules, no need to install. (in previous versions of Python2 the name was SimpleHTTPServer)

tutorial

Created from the command line

http.server supports direct invocation with the -m parameter of the Python interpreter.

Create the simplest HTTP server by executing the following command:

python -m http.server

The default listening port of the server is 8000, which supports custom port numbers:

python -m http.server 9000

The server is bound to all interfaces by default, and can be specified by -b/--bindspecifying an address, such as localhost:

python -m http.server --bind 127.0.0.1

The default working directory of the server is the current directory, and -d/--directorythe working directory can be specified through the parameter:

python -m http.server --directory /tmp/

Additionally, the CGI request handler can --cgibe enabled by passing a parameter:

python -m http.server --cgi

write code to create

http.server also supports calling in code, just import the corresponding classes and functions.

from http.server import SimpleHTTPRequestHandler
from http.server import CGIHTTPRequestHandler
from http.server import ThreadingHTTPServer
from functools import partial
import contextlib
import sys
import os


class DualStackServer(ThreadingHTTPServer):
    def server_bind(self):
        # suppress exception when protocol is IPv4
        with contextlib.suppress(Exception):
            self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
        return super().server_bind()


def run(server_class=DualStackServer,
        handler_class=SimpleHTTPRequestHandler,
        port=8000,
        bind='127.0.0.1',
        cgi=False,
        directory=os.getcwd()):
    """Run an HTTP server on port 8000 (or the port argument).

    Args:
        server_class (_type_, optional): Class of server. Defaults to DualStackServer.
        handler_class (_type_, optional): Class of handler. Defaults to SimpleHTTPRequestHandler.
        port (int, optional): Specify alternate port. Defaults to 8000.
        bind (str, optional): Specify alternate bind address. Defaults to '127.0.0.1'.
        cgi (bool, optional): Run as CGI Server. Defaults to False.
        directory (_type_, optional): Specify alternative directory. Defaults to os.getcwd().
    """

    if cgi:
        handler_class = partial(CGIHTTPRequestHandler, directory=directory)
    else:
        handler_class = partial(SimpleHTTPRequestHandler, directory=directory)

    with server_class((bind, port), handler_class) as httpd:
        print(
            f"Serving HTTP on {
      
      bind} port {
      
      port} "
            f"(http://{
      
      bind}:{
      
      port}/) ..."
        )
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            sys.exit(0)


if __name__ == '__main__':
    run(port=8000, bind='127.0.0.1')
  • server_class: server class
  • handler_class: request processing class
  • port:port
  • bind:IP
  • cgi: Whether to enable the CGI request handler
  • directory:Work list

example

Now that we know that http.server can quickly create an HTTP server, what project scenarios can it be applied to?

  1. Preview of small web projects in LAN
  • project directory
web:.
├─index.html
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    hello world
</body>
</html>
  • Switch to the directory cd web, execute the command python -m http.server, enter the address bar of the browser localhost:8000, and display:
hello world

For other users in the LAN, you can access it through your host IP + port number. If your host IP is 192.168.0.1, then send the URL 192.168.0.1:8000 to your colleagues or classmates, and they can also see index.html The content of the file to render.

  1. Port mapping for accessing remote server in local browser

If you connect to the remote server through VSCode, after using http.server to open a port, it will be automatically mapped to the local, so that you can view and download the remote server resources in the local browser. (In addition to VSCode, other tools should also be able to implement remote and local port mapping)

Notice

http.server only implements the most basic security review, please do not use it in a production environment.

reference

http.server official document

illustration

cover

[Artist] フカヒレ [P Station ID] 78142008

Guess you like

Origin blog.csdn.net/qq_42951560/article/details/124218348