一个简单的基于异步的web框架。
induction的Python项目详细描述
一个简单的基于异步的web框架。
感应是驱动异步电动机的现象。上图是 Tesla’s induction motor。
安装
pip install induction
用法示例
如果你知道express和/或Flask,你就会有宾至如归的感觉。
同步路由
frominductionimportInductionapp=Induction(__name__)@app.route('/')defindex(request):returnapp.render_template('index.html')
异步路由
fromasyncioimportcoroutinefrominductionimportInductionapp=Induction(__name__)@app.route('/slow'):@coroutinedefslow(request,response):yield fromasyncio.sleep(10)response.write('Hello, world!')
处理程序
处理程序用@app.route(url_pattern)修饰。路由由管理 Routes库。
处理程序有多种方法将数据发送回客户端:
- 返回:同步路由可以直接返回数据。返回值
传递给响应对象。支持的返回值是:
- 字符串或字节对象,它成为响应的主体。一个 添加了200 OK的默认状态和text/html的mimetype。
- 一个(response, headers, status)元组,按任意顺序排列,至少有 提供一个项目。headers可以是列表或措辞。
- 正在写入:可以定义处理程序以接受两个参数,request和 response。然后他们可以直接向响应写入数据。
Induction对象
Induction构造函数接受以下参数:
- name:应用程序的名称。
以及以下关键字参数:
- template_folder:要从中加载模板的文件夹的路径。 相对于当前工作目录,默认为'templates'。
以下方法可用于Induction实例:
route(path, **conditions):注册路由。本应用作 装饰工:
@app.route('/') def foo(request): return jsonify({})
before_request(func):先注册要调用的函数 请求处理程序。例如:
@app.before_request def set_some_header(request, response): request.uuid = str(uuid.uuid4()) response.add_header('X-Request-ID', request.uuid)
before_request函数按声明顺序调用。
当before_request函数返回None以外的内容时,所有 请求处理已停止,返回的数据将传递给 回应。
after_request(func)注册一个在所有请求之后要调用的函数 处理程序。工作方式类似于before_request。
handle_404(request, [response]):http 404错误的错误处理程序。
error_handler(exc_type):注册在 请求处理程序引发类型为exc_type的异常。异常处理函数 以请求、响应和异常对象为参数:
@app.error_handler(ValueError): def handle_value_error(request, response, exception): response.add_header("X-Exception", str(exception))
请注意,响应可能已部分发送到客户端。 根据应用程序的功能,设置头可能不安全 甚至向响应发送数据。
通过将exc_type设置为None,可以注册catch all错误处理程序 将处理所有未处理的异常:
@app.error_handler(None): def handle_exception(request, response, exception): # Send exception to Sentry client = raven.Client() client.captureException()
render_template(template_name_or_list, **context):加载第一个 匹配来自template_name_or_list的模板并使用 给定上下文。
响应对象
以下属性和方法可用于Response对象:
status,status_line:此的http状态代码和行 回应。
write(chunk, close=False, unchunked=False):将数据块写入 回应。
如果chunk是一个字符串,它将被编码为字节。
如果close是True,则对响应调用write_eof()。
如果unchunked是TrueaContent-Lengthheader,并且 写入块后将关闭响应。
redirect(location, status=302):使用 给定状态代码。
释放量
- 0.2(2014-09-25)
- 404错误默认返回HTML。
- 能够设置一个catch all错误处理程序,例如用于岗哨处理。
- 0.1(2014-09-19)
- 初次发布。