Bottle 框架源码学习 三
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Bottle 框架源码学习 三相关的知识,希望对你有一定的参考价值。
def run(app=None, server=‘wsgiref‘, host=‘127.0.0.1‘, port=8080, interval=1, reloader=False, quiet=False, plugins=None, debug=None, **kargs):
今天要学习一下bottle里是怎样打印debug信息的
run函数的倒数第二个参数是debug,默认为None
try: if debug is not None: _debug(debug)
如果设置了debug的值,且不为None,则运行_debug函数
_debug = debug
_debug函数是debug函数的别名,因为和run里的debug变量同名,为了区别,所以用_debug这个名称
def debug(mode=True): """ Change the debug level. There is only one debug level supported at the moment.""" global DEBUG if mode: warnings.simplefilter(‘default‘) DEBUG = bool(mode)
globa DEBUG这句的作用是声明DEBUG这个变量是全局变量,由于要修改它的值,如果不声明为全局变量,则会将DEBUG定义为本函数内的局部变量。
if mode: warnings.simplefilter(‘default‘)
warnings.simplefilter定义简单过滤器,如果mode为真,则warnings的过滤器为default,以下是几种过滤器参数,特别要说明的是error过滤器,如果应用了这个过滤器,一旦产生警告信息,则当成错误来处理,不再执行后面的语句。
Value
Disposition
"error"
turn matching warnings into exceptions
"ignore"
never print matching warnings
"always"
always print matching warnings
"default"
print the first occurrence of matching warnings for each location where the warning is issued
"module"
print the first occurrence of matching warnings for each module where the warning is issued
"once"
print only the first occurrence of matching warnings, regardless of location
好了,大概用法已经看懂,再看bottle是怎样应用的
# -*- coding=utf-8 -*- from bottle import Bottle, run app = Bottle() @app.route(‘/hello‘) def hello(): raise Exception("this is my error") return "Hello World!" run(app, host=‘localhost‘, port=8080, reloader=True, debug=True)
将debug设置为True, 并在hello函数里手工制造一个异常。
浏览器里访问http://localhost:8080/hello
结果如下:
Error: 500 Internal Server Error
Sorry, the requested URL ‘http://localhost:8080/hello‘ caused an error:
Internal Server Error
Exception:
Exception(‘this is my error‘,)
Traceback:
Traceback (most recent call last): File "C:\Python27\lib\site-packages\bottle.py", line 862, in _handle return route.call(**args) File "C:\Python27\lib\site-packages\bottle.py", line 1740, in wrapper rv = callback(*a, **ka) File "D:/myproject/bottleApp/main.py", line 8, in hello raise Exception("this is my error") Exception: this is my error
看模板源码是怎样设置的
<body> <h1>Error: {{e.status}}</h1> <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt> caused an error:</p> <pre>{{e.body}}</pre> %%if DEBUG and e.exception: <h2>Exception:</h2> <pre>{{repr(e.exception)}}</pre> %%end %%if DEBUG and e.traceback: <h2>Traceback:</h2> <pre>{{e.traceback}}</pre> %%end </body>
注:如果debug=False,则不会输出Traceback信息,生产环境一般是要关闭的,开发的时候打开方便排错。
以上是关于Bottle 框架源码学习 三的主要内容,如果未能解决你的问题,请参考以下文章