python网站发布
作者:互联网
""" /etc/python3 @File : IO_HTTP.py @Time : 2020/7/18 下午3:26 @Author : wangyongqi @Email : 92644827@qq.com @SOftware : PyCharm """ from socket import * from select import * import re class WebServer: def __init__(self,host='0.0.0.0',port=8000,html=None): self.host=host self.port=port self.html=html #做IO多路复用的并发模型 self.__rlist=[] self.__wlist=[] self.__xlist=[] self.create_socket() self.bind() def create_socket(self): self.sock=socket() self.sock.setblocking(False) def bind(self): self.address=(self.host,self.port) self.sock.bind(self.address) def start(self): self.sock.listen(5) print('Listen the port %d'%self.port) self.__rlist.append(self.sock) while True: rs,ws,xs=select(self.__rlist,self.__wlist,self.__xlist) for r in rs: if r is self.sock: connfd,addr=self.sock.accept() connfd.setblocking(False) self.__rlist.append(connfd) else: self.handle(r) #处理客户请求 def handle(self,connfd): request=connfd.recv(1024*1024).decode('utf8') pattern='[A-Z]+\s+(?P<info>/\S*)' result=re.match(pattern,request) if result: info=result.group('info') self.send_requst(connfd,info) else: #断开客户端 self.__rlist.remove(connfd) connfd.close() def send_requst(self,connfd,info): try: html = open(self.html+info,'rb') print(html) except : hsstml = """/HTTP/1.1 200 ok Content-tpe text/html 404 """ connfd.send(hsstml.encode()) self.__rlist.remove(connfd) else: html=html.read() hsstml = "/HTTP/1.1 200 ok\r\n" hsstml+="Content-tpe text/html\r\n" hsstml+="Content-Length:%d\r\n"%len(html) hsstml+='\r\n' hsstml=hsstml.encode() hsstml+=html connfd.send(hsstml) self.__rlist.remove(connfd) connfd.close() # html=html.read() # url=info[1:] # if url=='': # hsstml = """/HTTP/1.1 200 ok # Content-tpe text/html # # 404 # """ # connfd.send(hsstml.encode()) # self.__rlist.remove(connfd) # # else: # try: # html=open(url) # except FileNotFoundError: # hsstml = """/HTTP/1.1 200 ok # Content-tpe text/html # # 404 # """ # connfd.send(hsstml.encode()) # self.__rlist.remove(connfd) # else: # html=html.read() # hsstml = f"""/HTTP/1.1 200 ok # Content-tpe text/html # # {html} # """ # connfd.send(hsstml.encode()) # self.__rlist.remove(connfd) if __name__ == '__main__': """ 1.使用流程 2.那些量需要用户决定,怎么传入 那组网页 服务端地址 """ httpd=WebServer(host='0.0.0.0',port=8578,html='static') httpd.start()
标签:.__,python,self,hsstml,网站,发布,html,rlist,connfd 来源: https://www.cnblogs.com/yongqi-wang/p/13336790.html