python-17-miniweb服务器返回动态页面装饰器方式

  • 在目录下拥有一个文件夹保存了静态网页 ./static
  • 在目录下拥有一个文件夹保存了动态网页 ./templates
  • 对请求资源不正确的做出错误处理,返回状态号 404 Not Found
  • while True : 上一个客户断开后,可以接受新的客户连接
  • 发送完报文后要关闭与客户端建立的套接字连接
  • 三层装饰器的作用是建立一个字典的关系,字典名[请求的网址]=本地资源
import socket


class WebServer():
    def __init__(self):                                                  # 初始化,定义一个空字典
         tcp_server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
         tcp_server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
         tcp_server_socket.bind(('192.168.124.131',8080))
         tcp_server_socket.listen(128)
         self.tcp_server_socket=tcp_server_socket
         self.url_dict = {}

    def start(self):                             # 创建与客户端之间的套接字,并保证可以前一个套接字关闭后继续接收新的套接字
         while True:
             new_client_socket,ip_port=self.tcp_server_socket.accept()
             self.handle(new_client_socket,ip_port)

    def handle(self,new_client_socket,ip_port):                  # 导出请求报文中的 请求资源地址
          request_data=new_client_socket.recv(4096)
          request_text=request_data.decode()
          loc=request_text.find('\r\n')
          request_line=request_text[:loc]
          request_line_list=request_line.split(' ')
          request_path=request_line_list[1]
          self.judge(request_path,new_client_socket)

    def judge(self,request_path,new_client_socket):              # 判断资源地址是py还是其他,并且发送响应报文

          if request_path.endswith('.py'):
              self.dict_funcs()                                  # 启动字典函数,利用三层装饰器建立请求资源地址和本地资源的关系
              print(self.url_dict)
              if request_path in self.url_dict:                  # 判断请求的 py 资源是否在装饰好的字典中
                   func=self.url_dict[request_path]
                   response_body=func()
                   state='200 OK'
                   response_data=self.pinjie(response_body,state)          # 进行拼接
                   new_client_socket.send(response_data)
                   new_client_socket.close()
              else:
                  response_body='您访问的页面不存在'.encode()
                  state='404 Not Found'
                  response_data=self.pinjie(response_body,state)
                  new_client_socket.send(response_data)
                  new_client_socket.close()

          else:
              if request_path=='/':
                  request_path='/index.html'
              file_path='./static'+request_path
              try:
                  with open(file_path,'rb')as file:
                      response_body=file.read()
                      state='200 OK'
                      response_data=self.pinjie(response_body,state)
                      new_client_socket.send(response_data)
                      new_client_socket.close()
              except Exception as e:
                    print('找不到您请求的页面')
                    response_body='404 Not Found!'.encode()
                    state='404 Not Found'
                    response_data=self.pinjie(response_body,state)
                    new_client_socket.send(response_data)
                    new_client_socket.close()
                    return

    def pinjie(self,response_body,state):                              #  接受响应主体和状态,拼接响应报文并返回加密好的响应报文
          response_line='HTTP/1.1 %s\r\n'%state
          response_headle='Server: Python20WS/2.1\r\n'
          response_black='\r\n'
          response_data=(response_line+response_headle+response_black).encode()+response_body
          return response_data

    def dict_funcs(self):                              # 字典函数,利用三层装饰器建立 请求资源地址和本地资源 之间的关系

            def func_dict(key):                        # 三层装饰器 ----------------
                def func_out(value):                                             
                    self.url_dict[key]=value
                    def func_in():
                        return value()
                    return func_in
                return func_out                        # 三层装饰器 ----------------

            @func_dict('/index.py')
            def index():
                with open('./templates/index.html','rb')as file:
                    response_body=file.read()
                    return response_body

            @func_dict('/center.py')
            def center():
                with open('./templates/center.html', 'rb')as file:
                    response_body = file.read()
                    return response_body

            @func_dict('/update.py')
            def update():
                with open('./templates/update.html', 'rb')as file:
                    response_body = file.read()
                    return response_body

if __name__ == '__main__':
    ws=WebServer()
    ws.start()




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值