python中localhost上的HTTP删除请求

Posted

技术标签:

【中文标题】python中localhost上的HTTP删除请求【英文标题】:HTTP delete request on localhost in python 【发布时间】:2021-06-23 16:36:26 【问题描述】:

我正在尝试在 localhost 上构建客户端和服务器,并使用 python 中的请求模块实现获取、发布和删除 http 请求。我有这个用于服务器:

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs

names_dict = 'john': 'smith',
              'david': 'jones',
              'michael': 'johnson',
              'chris': 'lee'


class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.log_message("Incoming GET request...")
        try:
            name = parse_qs(self.path[2:])['name'][0]
        except:
            self.send_response_to_client(404, 'Incorrect parameters provided')
            self.log_message("Incorrect parameters provided")
            return

    if name in names_dict.keys():
        self.send_response_to_client(200, names_dict[name])
    else:
        self.send_response_to_client(404, 'Name not found')
        self.log_message("Name not found")

def do_POST(self):
    self.log_message('Incoming POST request...')
    data = parse_qs(self.path[2:])
    try:
        names_dict[data['name'][0]] = data['last_name'][0]
        self.send_response_to_client(200, names_dict)
    except KeyError:
        self.send_response_to_client(404, 'Incorrect parameters provided')
        self.log_message("Incorrect parameters provided")

def send_response_to_client(self, status_code, data):
    # Send OK status
    self.send_response(status_code)
    # Send headers
    self.send_header('Content-type', 'text/plain')
    self.end_headers()

    # Send the response
    self.wfile.write(str(data).encode())

server_address = ('127.0.0.1', 8080)
http_server = HTTPServer(server_address, RequestHandler)
http_server.serve_forever()

这个给客户:

import requests

r = requests.get("http://127.0.0.1:8080/", params="name":'michael')
print("Request method: GET, \
    Response status_code: , Response data: ".format(r.status_code, r.text))
r = requests.post("http://127.0.0.1:8080/", params = 'name':'peter', 'last_name':'peterson')
print("Request method: POST, \
    Response status_code: , Response data: ".format(r.status_code, r.text))
r = requests.delete("http://127.0.0.1:8080/", params='name':'chris', 'last_name':'lee')
print("Request method: DELETE, \
    Response status_code: , Response data: ".format(r.status_code, r.text))

如何在服务器文件中添加代码以根据名称和姓氏从字典中删除条目,然后像发布请求后一样在屏幕上打印新字典。

【问题讨论】:

【参考方案1】:

我不知道这是纯属巧合还是我们是同事。但我在我参加的课程中也有这个作业。删除并给客户端我已经实现的列表的方法是:

def do_DELETE(self):
    self.log_message('Incoming DELETE request...')

    try:
        name = parse_qs(self.path[2:])['name'][0]  
    except KeyError:
        self.send_response_to_client(404, self.path[2:])
        self.log_message("Incorrect parameters provided")
        return
        
    for key, value in names_dict.items():
        if name in names_dict.keys() or names_dict.values():
        
            if key == name:
                del names_dict[key]
                self.send_response_to_client(200, f'Name found and deleted names_dict')
                self.log_message("Name found and deleted")
                break
            elif value == name:
                del names_dict[key]
                self.send_response_to_client(200, f'Last Name found and deleted names_dict')
                self.log_message("Last Name found and deleted")
                
                break
    else:
        self.send_response_to_client(404, 'Name does not exist')
        self.log_message("Name does not exist")

【讨论】:

以上是关于python中localhost上的HTTP删除请求的主要内容,如果未能解决你的问题,请参考以下文章

删除 http://localhost:8000/product/[object%20Object] 500(内部服务器错误)

如何从 http://localhost:8123 中删除端口号以用作 http://localhost? [关闭]

localhost无法访问

删除了IIS上的连接

删除 http://localhost:3000/people/[object%20Object] 404(未找到)

如何从 docker 容器中的 python 脚本连接到 localhost 上的 mysql 数据库