web.py能条件判断的页面执行计时方法,web.py计时,编橙之家之前有贴出过关于


编橙之家之前有贴出过关于web.py 的页面执行计时的网友分享贴。那是用Python的装饰器实的web.py页面执行计时方法(页脚的 html注释显示执行时间)需要执行计时的位置还要加个装饰器,那样操作是比较麻烦的。

这次网友提供的是web.py能条件判断的页面执行计时方法,这次会自己判断是否是html或xml。如果满足条件就执行添加计时操作;否则就仅仅把耗时记录在context里面。

python 计时器

实现计时的中间件代码:

def timespent_processor(handler):           starttime = time.time()    result = handler()    web.ctx.timespent = timespent = time.time() - starttime    content_type = dict(web.ctx.headers).get("Content-Type")    xml_types = ("text/html", "application/xhtml+xml", "application/xml")    if content_type in xml_types:        result += "\n<!-- %d ms -->" % (timespent * 1000)    return resultapplication.add_processor(timespent_processor)

完整测试python源码

#!/usr/bin/env python#-*- coding:utf-8 -*-import timeimport jsonimport web# ----------# Processors# ----------def timespent_processor(handler):           starttime = time.time()    result = handler()    web.ctx.timespent = timespent = time.time() - starttime    content_type = dict(web.ctx.headers).get("Content-Type")    xml_types = ("text/html", "application/xhtml+xml", "application/xml")    if content_type in xml_types:        result += "\n<!-- %d ms -->" % (timespent * 1000)    return result# -----------# Application# -----------urls = ("/", "Home",        "/json/", "Json")application = web.application(urls, globals())application.add_processor(timespent_processor)# -----------# Controllers# -----------class Home(object):    def GET(self):        web.header("Content-Type", "text/html")        return "<h1>Hello, World</h1>"class Json(object):    def GET(self):        web.header("Content-Type", "application/json")        return {'title': "Hello, World"}# ------# Runner# ------if __name__ == "__main__":    application.run()

python 计时方法相关文章推荐:
Python datetime计时程序的实现方法
web.py页面执行计时,Python装饰器实现方法

编橙之家文章,

评论关闭