简体   繁体   English

HTTP 在 python 中的 localhost 上删除请求

[英]HTTP delete request on localhost in python

I'm trying to build client and server on localhost and implement get, post and delete http requests using requests module in python.I have this for server:我正在尝试在本地主机上构建客户端和服务器,并使用 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()

and this for client:这对于客户:

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))

How can I add code in server file to delete entry from dictionary based on name and last_name and after that print new dictionary on screen like after post request.如何在服务器文件中添加代码以根据名称和姓氏从字典中删除条目,然后像发布请求后一样在屏幕上打印新字典。

I don't know if it's pure coincidence or if we're colleagues.我不知道这是纯属巧合还是我们是同事。 But I also had this assignamment in the courses I take.但我在我参加的课程中也有这个作业。 The method to delete and give the client the list that I have implemented is:删除并给客户端我已经实现的列表的方法是:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM