Python 网络编程随笔

Posted ye雨寄北

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 网络编程随笔的主要内容,如果未能解决你的问题,请参考以下文章

python随笔

Python 网络编程随笔

python day6

python全栈 day09随笔

python网络爬虫学习随笔

Pygame - Python游戏编程入门