首页 > 编程语言 > 详细

Python 网络编程随笔

时间:2021-06-01 15:18:23      阅读:19      评论:0      收藏:0      [点我收藏+]
import socket
class Route(object):
    _routes = {}
    def __new__(cls,*args,**kwargs):
        if(not hasattr(cls,‘instance‘)):
            instance = super().__new__(cls)
            setattr(cls,"instance",instance)
        return getattr(cls,"instance")

    def __call__(self,route):
        def wrap(func):
            self._routes[route] = func
        return wrap

router = Route()

@router("/")
def index() -> str:
    with open(‘index.html‘,‘r‘) as f:
        content = f.read()
    return content
    
@router("/home")
def home() -> str:
    with open("home.html",‘r‘) as f:
        content = f.read()
    return content

if __name__ == "__main__":
    r = Route()
    print(r._routes)
    print("server start...")
    s = socket.socket()
    s.bind(("0.0.0.0",8888))
    s.listen(5)
    while 1:
        conn,addr = s.accept()
        print(addr)
        data = conn.recv(4096)
        print(data)
        header = str(data)
        try:
            method,route,_ = header.split("\\r\\n")[0].split(" ")
            content = Route._routes[route]()
            conn.send(bytes(f"HTTP/1.1 200 OK\r\nContent-Type:text/html;\r\nContent-Length:{len(content)}\r\n\r\n{content}",encoding="utf-8"))
        except KeyError:
            ...
    s.close()


    

  

Python 网络编程随笔

原文:https://www.cnblogs.com/xianning7/p/14836631.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!