
from webob import Request,Response,exc |
from wsgiref.simple_server import make_server |
from webob.dec import wsgify |
class Application: |
#路由表 |
ROUTEABLE = {} |
#注册 |
@classmethod |
def register(cls,path): |
def wrapper(handler): |
cls.ROUTEABLE[path] = handler |
return handler |
return wrapper |
@wsgify #装饰器 |
def __call__(self,request:Request) -> Response: #一个请求对应一个相应 |
try: |
return self.ROUTEABLE[request.path](request) |
except: |
raise exc.HTTPNotFound("您访问的页面被外星人劫持了") |
@Application.register('/') |
def index(request:Request): |
res = Response() |
res.body = '<h1>马哥教育欢迎大家</h1>'.encode() |
return res |
@Application.register('/python') |
def showpython(request:Request): |
res = Response() |
res.body = '<h1>马哥教育python欢迎大家</h1>'.encode() |
return res |
if __name__ == "__main__": |
httpd = make_server('0.0.0.0', 9000, Application())# 函数本身要求为可迭代对象 |
try: |
httpd.serve_forever() |
except Exception as e: |
print(e) |
except KeyboardInterrupt: |
print('stop') |
httpd.server_close() |



