[python]代码库
from webob import Response, Request
from wsgiref.simple_server import make_server
from webob.dec import wsgify
from webob.exc import HTTPNotFound
import logging
import re
class Router:
ROUTERTABLE = []
@classmethod
def register(cls, pattern):
def wrapper(handler):
cls.ROUTERTABLE.append((re.compile(pattern), handler))
return handler
return wrapper
# http://xxx/python/class/student/001
@Router.register(r'/python$')
def pythonhandler(request:Request):
return '<h1>magedu.com Python</h1>'
@Router.register(r'/.*$')
def indexhandler(request:Request): # bytes,String,response
return '<h1>magedu.com Index.html</h1>'
class App:
_Router = Router
@wsgify
def __call__(self, request:Request):
path = request.path
for pattern, handler in self._Router.ROUTERTABLE: #pattern是编译过的
matcher = pattern.match(path)
if matcher: #匹配成功
response = handler(request)
return response
raise HTTPNotFound('<h1>该网页被外星人劫持了</h1>') #404处理
with make_server('0.0.0.0', 8000, App()) as httpd: #创建server
print("Serving on port 8000...")
httpd.serve_forever()
初级程序员
by: 云代码会员 发表于:2021-11-12 12:41:06 顶(0) | 踩(0) 回复
666
回复评论