Python教程

Python 网络编程随笔

本文主要是介绍Python 网络编程随笔,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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 网络编程随笔的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!