[python]代码库
from wsgiref.simple_server import make_server
from webob import Request,Response,exc
from webob.dec import wsgify
class Application:
#路由表
ROUTETABLE = {}
@classmethod
def register(cls,path):
def wrapper(handler):
cls.ROUTETABLE[path] = handler
return handler
return wrapper
@wsgify
def __call__(self,request:Request) -> Response: # app = wsgify(app)
# return self.ROUTETABLE.get(request.path, self.notfound)(request)
try:
return self.ROUTETABLE[request.path](request)
except:
raise exc.HTTPNotFound("您访问的页面被外星人劫持了")
@Application.register('/')
def index(request:Request): # index = Application.register('/')(index)
res = Response()
# res.charset = 'gb2312'
res.body = "<h1>马哥教育欢迎大家</h1>".encode()
return res
@Application.register('/python')
def showpython(request:Request):
res = Response()
# res.charset = 'gb2312'
res.body = "<h1>马哥教育python欢迎大家</h1>".encode()
return res
if __name__ == "__main__":
httpd = make_server('127.0.0.1', 9000, Application())
print("Serving on port 8000...")
try:
httpd.serve_forever()
except Exception as e:
print(e)
except KeyboardInterrupt:
print('stop')
httpd.server_close()