我正在尝试用python创建一个简单的线程服务器。在浏览器中进行调用时,似乎发出了两个请求,这会导致脚本出错
我可以向urlparse
添加额外的检查,但我更愿意阻止第二次调用的发生
我想知道这是否是我的PHP脚本,所以我使用postman发送请求,但仍然存在相同的问题
更新:在最终发送后添加中断时,循环明显停止。奇怪的是,第一个请求似乎失败了,然后每隔一个请求客户机就有正确的数据
class ClientThread(Thread):
def __init__(self,ip,port):
Thread.__init__(self)
self.ip = ip
self.port = port
def run(self):
while True :
data = conn.recv(2048)
// it errors here stating index out of range.
// I can add checks, but would like to prevent/not detect this seccond request
parsed_url = urlparse(data.split()[1].decode("utf-8"))
dctParams = parse_qs(parsed_url.query)
if "ProductID" in dctParams:
sProductID = dctParams.get("ProductID")[0]
else:
print("Unable to find key. Continuing")
break #continue
print("Requested ProductID: ", sProductID, "found. Attempting to find matches")
bSuccess = True
try:
aOut = data_matrix.loc[sProductID].nlargest(10)
print("Request satisfied")
print(aOut)
print("\n\n")
except:
bSuccess = False
print("Error Finding product in data set")
byt = ""
if bSuccess:
byt = json.dumps({'Success': True, 'Data': aOut.to_dict()}).encode("utf-8")
else:
byt = json.dumps({'Success': False, 'Data': ''}).encode("utf-8")
# send headers
conn.send('HTTP/1.0 200 OK\r\n'.encode("utf-8"))
conn.send("Content-Type: application/json\r\n".encode("utf-8"))
sLenth = "Content-Length: " + str(len(byt))
sLenth += "\r\n\r\n"
conn.send(sLenth.encode("utf-8"))
# send the acutal json
conn.send(byt)
# Multithreaded Python server : TCP Server Socket Program Stub
TCP_IP = '0.0.0.0'
TCP_PORT = 12345
BUFFER_SIZE = 20 # Usually 1024, but we need quick response
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpServer.listen(4)
print("Multithreaded Python server : Waiting for connections from TCP clients...\n\r")
(conn, (ip,port)) = tcpServer.accept()
newthread = ClientThread(ip,port)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
这两个要求是什么?不,我会告诉你其中一个是索引,另一个是最喜欢的图标
您不能阻止浏览器发出任何潜在的不需要的请求,您所能做的就是使用适当的响应代码响应它们
相关问题 更多 >
编程相关推荐