python开启访问静态文件的简易服务器(miniserv.py)


有的时候,本地不想架构nginx或者apache,但是想访问一个前后端分离的静态文件,可以使用这个简单的python脚本。

可以直接本地开启一个访问静态文件的简易服务器,端口默认9413可以随便改,没被占用即可。

默认静态文件根目录是当前运行py文件同级的public目录。

新建一个public/index.html就可以演示

miniserv 简易服务器

#-*- coding: utf-8 -*- 

import socket
import re

from multiprocessing import Process


############################################################
#### author:    kc
#### since:     2021-03-08
#### name:      miniserv.py(迷你服务器)
#### describe:  可以直接本地开启一个访问静态文件的简易服务器
############################################################


# 监听本地端口
HTTP_SERVER_PORT = 9413

# 静态文件根目录
HTML_ROOT_DIR = "./public"


def request_handler(clientSocket):
    """
    处理客户端请求
    """
    # 获取客户端请求数据
    receiveData = clientSocket.recv(1024)
    print("request data:", receiveData)
    requestLines = receiveData.splitlines()
    
    # 解析请求报文
    requestFirst = requestLines[0]
    
    # 提取用户请求的文件名
    fileName = re.match(r"\w+ +(/[^ ]*) ", requestFirst.decode("utf-8")).group(1)

    if "/" == fileName:
        fileName = "/index.html"

    # 打开文件,读取内容
    try:
        file = open(HTML_ROOT_DIR + fileName, "rb")
    except IOError:
        responseFirst = "HTTP/1.1 404 Not Found\r\n"
        responseHeaders = "Server: My server\r\n"
        responseBody = "The file is not found!"
    else:
        fileData = file.read()
        file.close()

        # 构造响应数据
        responseFirst = "HTTP/1.1 200 OK\r\n"
        responseHeaders = "Server: My server\r\n"
        responseBody = fileData.decode("utf-8")

    response = responseFirst + responseHeaders + "\r\n" + responseBody
    print("response data:", response)

    # 向客户端返回响应数据
    clientSocket.send(bytes(response, "utf-8"))

    # 关闭客户端连接
    clientSocket.close()


if __name__ == "__main__":
    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serverSocket.bind(("", HTTP_SERVER_PORT))
    serverSocket.listen(128)


    print('miniserv 简易服务器已启动,等待连接中...')
    print('miniserv 访问地址:http://127.0.0.1:{}/'.format(HTTP_SERVER_PORT,))
    print()

    while True:
        clientSocket, clientAddress = serverSocket.accept()
        print("[%s, %s]已连接" % clientAddress)
        clientProcess = Process(target=request_handler, args=(clientSocket,))
        clientProcess.start()
        clientSocket.close()

原文链接:https://blog.yongit.com/note/886233.html