跳转到主要内容

一个基于asyncio的简单Web框架。

项目描述

Build Status

一个基于asyncio的简单Web框架。

Tesla's induction motor

感应是驱动异步电机的现象。上图是 特斯拉的感应电机

安装

pip install induction

使用示例

如果你熟悉 express 和/或 Flask,你会感到非常自在。

同步路由

from induction import Induction
app = Induction(__name__)

@app.route('/')
def index(request):
    return app.render_template('index.html')

异步路由

from asyncio import coroutine
from induction import Induction
app = Induction(__name__)

@app.route('/slow'):
@coroutine
def slow(request, response):
    yield from asyncio.sleep(10)
    response.write('Hello, world!')

处理器

处理器通过 @app.route(url_pattern) 装饰。路由由 Routes 库管理。

处理器有几种方式将数据发送回客户端

  • 返回:同步路由可以直接返回数据。返回值传递给响应对象。支持的返回值包括

    • 一个字符串或字节对象,该对象将成为响应的主体。默认状态为 200 OK,内容类型为 text/html

    • 一个由 (response, headers, status) 组成的元组,顺序任意,至少有一个元素。 headers 可以是一个列表或字典。

  • 写入:处理器可以定义接受两个参数,requestresponse。然后它们可以直接将数据写入响应。

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允许您注册一个捕获所有异常的通用错误处理器。

    @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对象上可用

  • statusstatus_line:此响应的HTTP状态码和行。

  • write(chunk, close=False, unchunked=False):将数据块写入响应。

    如果chunk是字符串,它将被编码为字节。

    如果closeTrue,则会在响应上调用write_eof()

    如果unchunkedTrue,将添加Content-Length标题,并在写入数据块后关闭响应。

  • redirect(location, status=302):使用给定的状态码重定向到location

版本

  • 0.2 (2014-09-25)

    • 默认情况下,404错误返回HTML。

    • 可以设置一个捕获所有错误的错误处理器,例如用于Sentry处理。

  • 0.1 (2014-09-19)

    • 初始版本。

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪一个,请了解更多关于安装包的信息。

源代码分发

induction-0.2.tar.gz (6.5 kB 查看哈希)

源代码

构建版本

induction-0.2-py3-none-any.whl (6.9 kB 查看哈希)

Python 3

由以下支持