Python 网络编程随笔

Python 网络编程随笔,第1张

概述importsocketclassRoute(object):_routes={}def__new__(cls,*args,**kwargs):if(nothasattr(cls,'instance')):instance=super().__new__(cls)setattr(cls,"instance",instance)returng
import socketclass 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 wraprouter = 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 contentif __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 网络编程随笔所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1185456.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存