首页 > 解决方案 > 如何使用 Python 套接字在 HTTP 服务器中实现 POST 请求

问题描述

我正在使用带有套接字的 Python 中为网页设计制作本地 HTTP 服务器,并且我已经实现了处理 GET 请求,但我不确定如何实现 POST 请求。有人可以帮我吗?

我试过的:

期望:

这是我处理传入请求的代码块:

    def handle_client(self, conn, addr):
        BUFSIZ = 8192
 
        while True:
            try:
                data = conn.recv(BUFSIZ).decode()
 
                if data:
                    lines = data.split('\r\n')
 
                    req_line = lines[0]
 
                    req_method = req_line.split(' ')[0]
 
                    if req_method == 'GET':
                        response_line = b""
                        response_header = b""
                        blank_line = b"\r\n"
                        response_body = b""
 
 
                        requested_file = req_line.split(' ')[1]
 
                        if requested_file == '/':
                            requested_file = '/index.html'
                        else:
                            pass
 
                        filepath = self.content_dir + requested_file
 
                        print(f'Initiating webpage {filepath}')
 
                        try:
                            with open(filepath, 'rb') as f:
                                response_body = f.read()
 
                            response_line = self.create_response_line(status_code=200)
                            response_header = self.create_headers()
                                        
                        
                        except Exception as e:
                            print(f'Something went wrong while trying to serve {filepath}')
 
                            response_line = self.create_response_line(status_code=404)
                            response_header = self.create_headers()
                            response_body = "<h1>{} {}</h1>".format(
                                404,
                                self.status_codes[404]
                            ).encode('utf8')
 
                        response = b""
 
                        response += response_line
                        response += response_header
                        response += blank_line
                        response += response_body
 
                        conn.send(response)
 
                        conn.close()
 
                        break
                    else:
                        print(f'Unsupported request method: {req_method}')
                
                else: break
            
            except KeyboardInterrupt:
                self.sv.shutdown()

这是整个脚本:https ://pastebin.com/8ievdfay

标签: pythonsocketshttpserverpython-requests

解决方案


推荐阅读