it编程 > 前端脚本 > Python

Python 基于http.server模块实现简单http服务的代码举例

21人参与 2025-08-20 Python

测试环境

win11专业版

python 3.9

代码实现

# -*- coding:utf-8 -*-
import json
import traceback
import uuid
from http.server import httpserver, threadinghttpserver, basehttprequesthandler
from urllib.parse import urlparse, parse_qs
class myhttprequesthandler(basehttprequesthandler):
    def _send_response(self, status_code, content_type, body):
        '''发送响应信息'''
        self.send_response(status_code)
        self.send_header('content-type', content_type)
        self.send_header('cache-control', 'no-store')  # 防止缓存旧编码响应
        self.end_headers()
        self.wfile.write(body.encode('utf-8'))
    def _handle_home(self):
        '''访问主页请求处理'''
        html = '<meta http-equiv="content-type" content="text/html; charset=utf-8"><h1>home page</h1>'
        self._send_response(200, 'text/html; charset=utf-8', html)
    def _handle_404(self):
        '''请求不存在资源处理'''
        # json_respose = {"success": false, "message": "not found"}
        # self._send_response(404, 'application/json;charset=utf-8', json.dumps(json_respose))
        # content-type 指定 charset=utf-8 可避免浏览器get请求,界面中文显示乱码问题
        self._send_response(404, 'text/html; charset=utf-8', "<h1>404 not found</h1>")
    def _handle_login(self, login_req_data):
        '''处理登录请求'''
        try:
            data = json.loads(login_req_data)
            username = data.get('username')
            password = data.get('password')
            ip = data.get('ip')
            response = {
                'code': 0,
                'token': uuid.uuid4().hex,
                'description': 'success'
            }
            self._send_response(200, 'application/json; charset=utf-8', json.dumps(response))
        except exception as e:
            error_msg = traceback.format_exc()
            print(error_msg)
            response = {
                'code': 1,
                'token': '',
                'description': error_msg
            }
            self._send_response(500, 'application/json; charset=utf-8', json.dumps(response))
    def do_get(self):
        '''处理get请求'''
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        query_params = parse_qs(parsed_path.query)  # 获取url携带的查询参数
        # print('收到get请求参数:', query_params)
        if path == '/':
            self._handle_home()
        else:
            self._handle_404()
    def do_post(self):
        '''处理post请求'''
        content_length = int(self.headers['content-length'])
        post_data = self.rfile.read(content_length)
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        query_params = parse_qs(parsed_path.query)  # 获取url 查询参数
        # print("收到post数据:", post_data.decode())
        # 路由匹配逻辑
        if path == '/':
            self._handle_home()
        elif path == '/north/login':
            self._handle_login(post_data.decode())
        else:
            self._handle_404() 
if __name__ == '__main__':
    # server = httpserver(('0.0.0.0', 8000), myhandler) # 阻塞式运行
    server = threadinghttpserver(('localhost', 8000), myhttprequesthandler)
    print('正在启动服务,访问地址:http://localhost:8000')
    server.serve_forever()

扩展:如果我们希望服务在处理请求的时,调用其它类实例的方法,或者更新其它类实例的属性,咋处理呢?

答案:将其它类实例初始化为requesthandler的类属性,然后在相关请求处理函数中进行调用

示例

class subsystem():
    def __init__(self, http_server_port):
        self.http_server_port = http_server_port
        self.server = threadinghttpserver(('0.0.0.0', self.http_server_port), lambda *args: myhttprequesthandler(self, *args))
        self.north_server_info = {}
    def start_http_server(self):
        self.server.serve_forever()
    def push_data(self, data):
        '''测试函数'''
        logger.info(f'pushing data to server')
    def update_north_server_info(self, data):
        '''测试函数'''
        self.north_server_info[data.get('ip')] = data
class myhttprequesthandler(basehttprequesthandler):
    def __init__(self, subsystem, *args, **kwargs):
        self.subsystem = subsystem  # 保存subsystem实例引用
        super().__init__(*args, **kwargs)
    # ....略
    def _handle_login(self, login_req_data):
        '''处理登录请求'''
        try:
            data = json.loads(login_req_data)
            username = data.get('username')
            password = data.get('password')
            ip = data.get('ip')
            response = {
                'code': 0,
                'token': uuid.uuid4().hex,
                'description': 'success'
            }
            self.subsystem.push_data('')
            self.subsystem.update_north_server_info({'username': username, 'password': password, 'ip': ip})
            self._send_response(200, 'application/json; charset=utf-8', json.dumps(response))
        except exception as e:
            error_msg = traceback.format_exc()
            logger.error(error_msg)
            response = {
                'code': 1,
                'token':'',
                'description': error_msg
            }
            self._send_response(500, 'application/json; charset=utf-8', json.dumps(response))
# 测试
if __name__ == '__main__':
    http_port = 8000
    for i in range(2):
        system = subsystem(http_port)
        thread = threading.thread(target=system.start_http_server)
        thread.start()
        http_port += 1

相关介绍

模块简介

http.server 模块定义了用于实现http服务器(web服务器)的类。

其中一个类,httpserversocketserver.tcpserver子类。它创建并监听http套接字,将请求分派给处理程序。创建和运行服务器的代码示例如下:

def run(server_class=httpserver, handler_class=basehttprequesthandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

类及相关函数简介

httpserverthreadinghttpserver 必须在实例化时给它一个requesthandlerclass,此模块提供了三种不同的变体:

参考链接

https://docs.python.org/3.9/library/http.server.html

到此这篇关于python 基于http.server模块实现简单http服务的文章就介绍到这了,更多相关python http.server模块http服务内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

TensorFlow 张量操作的实现

08-20

Python自动化处理PDF文档的操作完整指南

08-20

Python常用标准库模块及查询使用方法

08-20

基于Python实现自动化邮件发送系统的完整指南

08-20

从基础到高级解析Python字符串变量插值

08-20

Python实现固定列宽文本格式化终极指南

08-20

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论