gpt4 book ai didi

python - 尝试在 python 服务器中执行 DELETE 方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:06 27 4
gpt4 key购买 nike

这是我第一次使用(或尝试)使用 Python。我想发布/获取和删除。POST 和 GET 运行良好,但当我尝试删除已发布的内容时,我感到非常头疼。你能给点启发吗?提前致谢!

import time
import BaseHTTPServer
import cgi


HOST_NAME = '0.0.0.0'
PORT_NUMBER = 8000

datastorage = []

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()

def do_POST(s):
s.send_response(200)
s.wfile.write("Ok")
contentLengthAsList = s.headers.getheaders('content-length')
contentLengthAsInt = int(contentLengthAsList[0])

x = cgi.parse_qs(s.rfile.read(contentLengthAsInt), keep_blank_values=1)
datastorage.append(x['myHttpData'][0])

print(datastorage)
s.end_headers()

def do_GET(s):
"""Respond to a GET request."""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("<html><head><title>MyPage</title></head>")
s.wfile.write("<body><p>The messages</p>")
for x in range(len(datastorage)):
s.wfile.write("<form action='/' method='DELETE'>"+datastorage[x]+"<input type='hidden' name='index' value='x'/><input type='submit' value='Remove'/></form></br>")
s.wfile.write("</body></html>")

def do_DELETE(s):
global datastorage
print 'That is working'
contentLengthAsList = s.headers.getheaders('content-length')
contentLengthAsInt = int(contentLengthAsList[0])

x = cgi.parse_qs(s.rfile.read(contentLengthAsInt), keep_blank_values=1)
datastorage = datastorage.pop(x)

s.send_response(301) #Moved Permanently
s.send_header("location", "/")
s.end_headers()



if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)`

最佳答案

您可能以错误的方式解析输入:

    x = cgi.parse_qs(s.rfile.read(contentLengthAsInt), keep_blank_values=1)

我明白了:

curl -X POST http://localhost:8000/ -H myHttpData:zumba -F jwf=jwf

-

127.0.0.1 - - [13/Sep/2017 19:31:13] "POST / HTTP/1.1" 200 -
{'--------------------------df32aa80f10efd75\r\nContent-Disposition: form-data': [''], ' name': ['"jwf"\r\n\r\njwf\r\n--------------------------df32aa80f10efd75--\r\n']}

这是一种发布表单的“现代”方式。尝试更简单的格式 ( application/x-www-form-urlencoded ) 或弄清楚如何解析 multipart/form-data有表单边界

关于python - 尝试在 python 服务器中执行 DELETE 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20330481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com