1.小知识
werkzeug 实现 web server
Flask 底层运行
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
class Short(object):
def __call__(self, environ, start_response):
request = Request(environ)
text = 'hello, %s' %(request.args.get('a', ''))
response = Response(text, mimetype='text/plain')
return response(environ, start_response)
if __name__ == '__main__':
app = Short()
run_simple('0.0.0.0', 5000, app)
返回 hello,
如果加参数如 url为 127.0.0.1:5000?a=hello
返回 hello, hello
类中的 self 为实例化对象本身
2.全局异常捕捉器
flask == 1.0
在主程序文件
@app.errorhandler(Exception)
def framework_error(e):
if isinstance(e, APIException):
return e
if isinstance(e, HTTPException):
code = e.code
msg = e.description
error_code = 1007
return APIException(code, msg, error_code)
else:
# 调试模式
if not app.config['DEBUG']:
return ServerError()
else:
raise e
if __name__ == '__main__':
app.run(debug=True)