import web
urls = ("/.*", "hello")
app = web.application(urls, globals())
class hello:
def GET(self):
return 'Hello, world!'
if __name__ == "__main__":
app.run()
def run(self, *middleware): return wsgi.runwsgi(self.wsgifunc(*middleware))
import web
class hello:
def GET(self):
return 'Hello, world!'
urls = ("/.*", "hello")
app = web.application(urls, globals())
application = app.wsgifunc()
app = web.application(urls, globals()) application = app.wsgifunc()
class application:
def __init__(self, mapping=(), fvars={}, autoreload=None):
if autoreload is None:
autoreload = web.config.get('debug', False)
self.init_mapping(mapping)
self.fvars = fvars
self.processors = []
self.add_processor(loadhook(self._load))
self.add_processor(unloadhook(self._unload))
if autoreload:
...
def init_mapping(self, mapping): self.mapping = list(utils.group(mapping, 2))
urls = ("/", "Index",
"/hello/(.*)", "Hello",
"/world", "World")
self.mapping = [["/", "Index"],
["/hello/(.*)", "Hello"],
["/world", "World"]]
self.add_processor(loadhook(self._load)) self.add_processor(unloadhook(self._unload))
def session_hook(): web.ctx.session = session app.add_processor(web.loadhook(session_hook))
def wsgifunc(self, *middleware):
"""Returns a WSGI-compatible function for this application."""
...
for m in middleware:
wsgi = m(wsgi)
return wsgi
def wsgi(env, start_resp):
# clear threadlocal to avoid inteference of previous requests
self._cleanup()
self.load(env)
try:
# allow uppercase methods only
if web.ctx.method.upper() != web.ctx.method:
raise web.nomethod()
result = self.handle_with_processors()
if is_generator(result):
result = peep(result)
else:
result = [result]
except web.HTTPError, e:
result = [e.data]
result = web.safestr(iter(result))
status, headers = web.ctx.status, web.ctx.headers
start_resp(status, headers)
def cleanup():
self._cleanup()
yield '' # force this function to be a generator
return itertools.chain(result, cleanup())
for m in middleware:
wsgi = m(wsgi)
return wsgi
self._cleanup() self.load(env)
try:
# allow uppercase methods only
if web.ctx.method.upper() != web.ctx.method:
raise web.nomethod()
result = self.handle_with_processors()
if is_generator(result):
result = peep(result)
else:
result = [result]
except web.HTTPError, e:
result = [e.data]
result = web.safestr(iter(result))
status, headers = web.ctx.status, web.ctx.headers
start_resp(status, headers)
def cleanup():
self._cleanup()
yield '' # force this function to be a generator
return itertools.chain(result, cleanup())
def loadhook(h):
def processor(handler):
h()
return handler()
return processor
def unloadhook(h):
def processor(handler):
try:
result = handler()
is_generator = result and hasattr(result, 'next')
except:
# run the hook even when handler raises some exception
h()
raise
if is_generator:
return wrap(result)
else:
h()
return result
def wrap(result):
def next():
try:
return result.next()
except:
# call the hook at the and of iterator
h()
raise
result = iter(result)
while True:
yield next()
return processor
def handle_with_processors(self):
def process(processors):
try:
if processors:
p, processors = processors[0], processors[1:]
return p(lambda: process(processors))
else:
return self.handle()
except web.HTTPError:
raise
except (KeyboardInterrupt, SystemExit):
raise
except:
print >> web.debug, traceback.format_exc()
raise self.internalerror()
# processors must be applied in the resvere order. (??)
return process(self.processors)
self.add_processor(loadhook(self._load)) self.add_processor(unloadhook(self._unload))
self.processors = [loadhook(self._load), unloadhook(self._unload)]
self.processors = [load_processor, unload_processor]
def handle_with_processors(self):
def process(processors):
try:
if processors: # 位置2
p, processors = processors[0], processors[1:]
return p(lambda: process(processors)) # 位置3
else:
return self.handle() # 位置4
except web.HTTPError:
raise
...
# processors must be applied in the resvere order. (??)
return process(self.processors) # 位置1
self.processors = [load_processor, unload_processor]
return load_processor(lambda: process([unload_processor]))
def load_processor(lambda: process([unload_processor])): self._load() return process([unload_processor]) # 就是参数的lambda函数
return unload_processor(lambda: process([]))
def unload_processor(lambda: process([])):
try:
result = process([]) # 参数传递进来的lambda函数
is_generator = result and hasattr(result, 'next')
except:
# run the hook even when handler raises some exception
self._unload()
raise
if is_generator:
return wrap(result)
else:
self._unload()
return result
self._load()
self.handle()
self._unload()
def handle(self): fn, args = self._match(self.mapping, web.ctx.path) return self._delegate(fn, self.fvars, args)
def _match(self, mapping, value):
for pat, what in mapping:
if isinstance(what, application): # 位置1
if value.startswith(pat):
f = lambda: self._delegate_sub_application(pat, what)
return f, None
else:
continue
elif isinstance(what, basestring): # 位置2
what, result = utils.re_subm('^' + pat + '$', what, value)
else: # 位置3
result = utils.re_compile('^' + pat + '$').match(value)
if result: # it's a match
return what, [x for x in result.groups()]
return None, None
fn, args = self._match(self.mapping, web.ctx.path) return self._delegate(fn, self.fvars, args)
def _delegate(self, f, fvars, args=[]):
def handle_class(cls):
meth = web.ctx.method
if meth == 'HEAD' and not hasattr(cls, meth):
meth = 'GET'
if not hasattr(cls, meth):
raise web.nomethod(cls)
tocall = getattr(cls(), meth)
return tocall(*args)
def is_class(o): return isinstance(o, (types.ClassType, type))
if f is None:
raise web.notfound()
elif isinstance(f, application):
return f.handle_with_processors()
elif is_class(f):
return handle_class(f)
elif isinstance(f, basestring):
if f.startswith('redirect '):
url = f.split(' ', 1)[1]
if web.ctx.method == "GET":
x = web.ctx.env.get('QUERY_STRING', '')
if x:
url += '?' + x
raise web.redirect(url)
elif '.' in f:
mod, cls = f.rsplit('.', 1)
mod = __import__(mod, None, None, [''])
cls = getattr(mod, cls)
else:
cls = fvars[f]
return handle_class(cls)
elif hasattr(f, '__call__'):
return f()
else:
return web.notfound()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有