talos-api


Nametalos-api JSON
Version 1.3.7 PyPI version JSON
download
home_pagehttps://gitee.com/wu.jianjun/talos
SummaryA Falcon Base, Powerful RESTful API Framework, with SQLAlchemy integrated
upload_time2024-10-15 02:51:10
maintainerNone
docs_urlNone
authorRoy
requires_pythonNone
licenseApache License 2.0
keywords talos automation restful rest api celery sqlalchemy falcon
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            talos project[^ 1]
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
![](https://img.shields.io/badge/language-python-orang.svg)
![](https://img.shields.io/pypi/dm/talos-api?style=flat)

=======================

[TOC]



## 特性

https://gitee.com/wu.jianjun/talos/tree/master/release

项目是主要基于falcon和SQLAlchemy封装,提供常用的项目工具,便于用户编写API服务
项目提供了工具talos_generator,可以自动为您生成基于talos的api应用,并且目录结构基于python标准包管理

* 基于falcon,高效
* 使用SQLAlchemy作为数据库后端,快速切换数据库
* 项目生成工具
* 快速RESTful CRUD API开发
* filters,pagination,orders支持
* validation数据校验
* 异步任务集成[celery]
* 定时任务集成[celery]
* 频率限制
* 国际化i18n支持
* SMTP邮件、AD域、CSV导出、缓存等常用模块集成

首先安装talos,运行talos生成工具生成项目

推荐通过pip安装

```bash
pip install talos-api
```

或者通过源码安装

```bash
python setup.py install
```



## 项目生成

安装talos后,会生成talos_generator工具,此工具可以为用户快速生成业务代码框架

```bash
> talos_generator
> 请输入项目生成目录:./
> 请输入项目名称(英):cms
> 请输入生成类型[project,app,其他内容退出]:project
> 请输入项目版本:1.2.4
> 请输入项目作者:Roy
> 请输入项目作者Email:roy@test.com
> 请输入项目启动配置目录:./etc #此处填写默认配置路径,相对路径是相对项目文件夹,也可以是绝对路径
> 请输入项目DB连接串:postgresql+psycopg2://postgres:123456@127.0.0.1/testdb [SQLAlchemy的DB连接串]
### 创建项目目录:./cms
### 创建项目:cms(1.2.4)通用文件
### 创建启动服务脚本
### 创建启动配置:./etc/cms.conf
### 创建中间件目录
### 完成
> 请输入生成类型[project,app,其他内容退出]:app # 生成的APP用于编写实际业务代码,或手动编写
### 请输入app名称(英):user
### 创建app目录:./cms/cms/apps
### 创建app脚本:user
### 完成
> 请输入生成类型[project,app,其他内容退出]:
```

项目生成后,修改配置文件,比如**./etc/cms.conf的application.names配置,列表中加入"cms.apps.user"即可启动服务器进行调试**




## 开发调试
启动项目目录下的server/simple_server.py即可进行调试



## 生产部署
  - 源码打包

```bash
pip install wheel
python setup.py bdist_wheel
pip install cms-1.2.4-py2.py3-none-any.whl
```

  - 启动服务:

```bash
# Linux部署一般配置文件都会放在/etc/cms/下,包括cms.conf和gunicorn.py文件
# 并确保安装gunicorn
pip install gunicorn
# 步骤一,导出环境变量:
export CMS_CONF=/etc/cms/cms.conf
# 步骤二,
gunicorn --pid "/var/run/cms.pid" --config "/etc/cms/gunicorn.py" "cms.server.wsgi_server:application"
```



## API开发引导

### 基础开发步骤

#### 设计数据库

略(talos要求至少有一列唯一性,否则无法提供item型操作)

#### 导出数据库模型

talos中使用的是SQLAlchemy,使用表操作需要将数据库导出为python对象定义,这样做的好处是

1. 确定表结构,形成应用代码与数据库之间的版本对应
2. 便于编程中表达数据库操作,而并非使用字符串
3. SQLAlchemy的多数据库支持,强大的表达能力

```bash
pip install sqlacodegen
sqlacodegen postgresql+psycopg2://postgres:123456@127.0.0.1/testdb --outfile models.py
```

生成的models.py内容大致如下:

```python
# coding=utf-8

from __future__ import absolute_import

from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'user'

    id = Column(String(36), primary_key=True)
    name = Column(String(63), nullable=False)
```

当然这个导出操作如果在足够熟悉的情况下可以手动编写,不需要导出工具

#### 数据库模型类的魔法类

将导出的文件表内容复制到cms.db.models.py中,并为每个表设置DictBase基类继承

models.py文件中,每个表对应着一个class,这使得我们在开发业务处理代码时能明确表对应的处理,但在接口返回中,我们通常需要转换为json,因而,我们需要为models.py中的每个表的类增加一个继承关系,以便为它提供转换的支持

处理完后的models.py文件如下:

```python
# coding=utf-8

from __future__ import absolute_import

from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
from talos.db.dictbase import DictBase

Base = declarative_base()
metadata = Base.metadata

class User(Base, DictBase):
    __tablename__ = 'user'

    id = Column(String(36), primary_key=True)
    name = Column(String(63), nullable=False)

class UserPhoneNum(Base, DictBase):
    __tablename__ = 'user_phone'

    user_id = Column(String(63), nullable=False, primary_key=True)
    phone = Column(String(63), nullable=False, primary_key=True)
    description = Column(String(255), nullable=True)
```

继承了这个类之后,不仅提供了转换接口json的能力,还提供了字段提取的能力,此处没有指定字段提取,则意味着默认使用表的所有字段(list和被其他表外键引用时默认不包含外键字段),如果需要自定义字段,可以在类中配置字段提取:

```python
class User(Base, DictBase):
    __tablename__ = 'user'
    # 用于控制获取列表时字段返回
    attributes = ['id', 'name']
    # 用于控制获取详情时字段返回
    detail_attributes = attributes
    # 用于控制被其他资源外键引用时字段返回
    summary_attributes = ['name']
    
    id = Column(String(36), primary_key=True)
    name = Column(String(63), nullable=False)
```
**指定attributes/detail_attributes/summary_attributes是非常有效的字段返回控制手段,减少返回的信息,可以减少服务器传输的压力,不仅如此,如果此处有外键relationship时,指定各attributes属性还可以有效的控制数据库对于外键的查询效率** [^ 9]

> 扩展阅读:
>
> 一个较为常见的场景,某系统设计有数据库表如下:
> User -> PhoneNum/Addresses, 一个用户对应多个电话号码以及多个地址
> Tag,标签表,一个资源可对应多个标签
> Region -> Tag,地域表,一个地域有多个标签
> Resource -> Region/Tag,资源表,一个资源属于一个地域,一个资源有多个标签
>
> 用models表示大致如下:
>
> ```python
> class Address(Base, DictBase):
>     __tablename__ = 'address'
>     attributes = ['id', 'location', 'user_id']
>     detail_attributes = attributes
>     summary_attributes = ['location']
> 
>     id = Column(String(36), primary_key=True)
>     location = Column(String(255), nullable=False)
>     user_id = Column(ForeignKey(u'user.id'), nullable=False)
> 
>     user = relationship(u'User')
>     
> class PhoneNum(Base, DictBase):
>     __tablename__ = 'phone'
>     attributes = ['id', 'number', 'user_id']
>     detail_attributes = attributes
>     summary_attributes = ['number']
> 
>     id = Column(String(36), primary_key=True)
>     number = Column(String(255), nullable=False)
>     user_id = Column(ForeignKey(u'user.id'), nullable=False)
> 
>     user = relationship(u'User')
>     
> class User(Base, DictBase):
>     __tablename__ = 'user'
>     attributes = ['id', 'name', 'addresses', 'phonenums']
>     detail_attributes = attributes
>     summary_attributes = ['name']
> 
>     id = Column(String(36), primary_key=True)
>     name = Column(String(255), nullable=False)
>     
>     addresses = relationship(u'Address', back_populates=u'user', lazy=False, uselist=True, viewonly=True)
>     phonenums = relationship(u'PhoneNum', back_populates=u'user', lazy=False, uselist=True, viewonly=True)
>     
> class Tag(Base, DictBase):
>     __tablename__ = 'tag'
>     attributes = ['id', 'res_id', 'key', 'value']
>     detail_attributes = attributes
>     summary_attributes = ['key', 'value']
> 
>     id = Column(String(36), primary_key=True)
>     res_id = Column(String(36), nullable=False)
>     key = Column(String(36), nullable=False)
>     value = Column(String(36), nullable=False)
> 
> class Region(Base, DictBase):
>     __tablename__ = 'region'
>     attributes = ['id', 'name', 'desc', 'tags', 'user_id', 'user']
>     detail_attributes = attributes
>     summary_attributes = ['name', 'desc']
> 
>     id = Column(String(36), primary_key=True)
>     name = Column(String(255), nullable=False)
>     desc = Column(String(255), nullable=True)
>     user_id = Column(ForeignKey(u'user.id'), nullable=True)
>     user = relationship(u'User')
> 
>     tags = relationship(u'Tag', primaryjoin='foreign(Region.id) == Tag.res_id',
>         lazy=False, viewonly=True, uselist=True)
> 
> class Resource(Base, DictBase):
>     __tablename__ = 'resource'
>     attributes = ['id', 'name', 'desc', 'tags', 'user_id', 'user', 'region_id', 'region']
>     detail_attributes = attributes
>     summary_attributes = ['name', 'desc']
> 
>     id = Column(String(36), primary_key=True)
>     name = Column(String(255), nullable=False)
>     desc = Column(String(255), nullable=True)
>     user_id = Column(ForeignKey(u'user.id'), nullable=True)
>     region_id = Column(ForeignKey(u'region.id'), nullable=True)
>     user = relationship(u'User')
>     region = relationship(u'region')
> 
>     tags = relationship(u'Tag', primaryjoin='foreign(Resource.id) == Tag.res_id',
>         lazy=False, viewonly=True, uselist=True)
> ```
>
> 如上,user作为最底层的资源,被region引用,而region又被resource使用,导致层级嵌套极多,在SQLAlchmey中,如果希望快速查询一个列表资源,一般而言我们会在relationship中加上lazy=False,这样就可以让信息在一次sql查询中加载出来,而不是每次访问外键属性再发起一次查询。问题在于,lazy=False时sql被组合为一个SQL语句,relationship每级嵌套会被展开,实际数据库查询结果将是乘数级:num_resource\*num_resource_user\*num_resource_user_address\*num_resource_user_phonenum\*num_region\*num_region_user_address\*num_region_user_phonenum...
>
> 较差的情况下可能回导致resource表只有1k数量级,而本次查询结果却是1000 \* 1k级
> 通常我们加载resource时,我们并不需要region.user、region.tags、user.addresses、user.phonenums等信息,通过指定summary_attributes来防止数据过载(需要启用CONF.dbcrud.dynamic_relationship,默认启用),这样我们得到的SQL查询是非常快速的,结果集也保持和resource一个数量级



#### 增删改查的资源类

在cms.db中新增resource.py文件,内容如下:

```python
# coding=utf-8

from __future__ import absolute_import

from talos.db.crud import ResourceBase

from cms.db import models


class User(ResourceBase):
    orm_meta = models.User
    _primary_keys = 'id'


class UserPhoneNum(ResourceBase):
    orm_meta = models.UserPhoneNum
    _primary_keys = ('user_id', 'phone')
```

完成此项定义后,我们可以使用resource.User来进行用户表的增删改查,而这些功能都是ResourceBase默认提供的能力
可以看到我们此处定义了orm_meta和_primary_keys两个类属性,除此以外还有更多类属性可以帮助我们快速配置应用逻辑

| 类属性                          | 默认值 | 描述                                                         |
| ------------------------------- | ------ | ------------------------------------------------------------ |
| orm_meta                        | None   | 资源操作的SQLAlchmey Model类[表]                             |
| orm_pool                        | None   | 指定资源使用的数据库连接池,默认使用defaultPool,实例初始化参数优先于本参数 |
| _dynamic_relationship           | None   | 是否根据Model中定义的attribute自动改变load策略,不指定则使用配置文件默认(True) |
| _dynamic_load_method            | None   | 启用动态外键加载策略时,动态加载外键的方式,默认None,即使用全局配置(全局配置默认joinedload) <br/> joinedload 简便,在常用小型查询中响应优于subqueryload  <br/>subqueryload 在大型复杂(多层外键)查询中响应优于joinedload |
| _detail_relationship_as_summary | None   | 资源get获取到的第一层级外键字段级别是summary级,则设置为True,否则使用配置文件默认(False) |
| _primary_keys                   | 'id'   | 表对应的主键列,单个主键时,使用字符串,多个联合主键时为字符串列表,这个是业务主键,意味着你可以定义和数据库主键不一样的字段(前提是要确定这些字段是有唯一性的) |
| _default_filter                 | {}     | 默认过滤查询,常用于软删除,比如数据删除我们在数据库字段中标记为is_deleted=True,那么我们再次list,get,update,delete的时候需要默认过滤这些数据的,等价于默认带有where is_delete = True |
| _default_order                  | []     | 默认排序,查询资源时被应用,('name', '+id', '-status'), +表示递增,-表示递减,默认递增 |
| _validate                       | []     | 数据输入校验规则,为talos.db.crud.ColumnValidator对象列表    |

一个validate示例如下:

```python
   ColumnValidator(field='id',
                   validate_on=['create:M']),
   ColumnValidator(field='name',
                   rule='1, 63',
                   rule_type='length',
                   validate_on=['create:M', 'update:O']),
   ColumnValidator(field='enabled',
                   rule=validator.InValidator(['true', 'false', 'True', 'False'])
                   converter=converter.BooleanConverter(),
                   validate_on=['create:M', 'update:O']),
```

ColumnValidator可以定义的属性如下:

| 属性         | 类型                                           | 描述                                                         |
| ------------ | ---------------------------------------------- | ------------------------------------------------------------ |
| field        | 字符串                                         | 字段名称                                                     |
| rule         | validator对象 或 校验类型rule_type所需要的参数 | 当rule是validator类型对象时,忽略 rule_type参数              |
| rule_type    | 字符串                                         | 用于快速定义校验规则,默认regex,可选类型有callback,regex,email,phone,url,length,in,notin,integer,float,type |
| validate_on  | 数组                                           | 校验场景和必要性, eg. ['create: M', 'update:O'],表示此字段在create函数中为必要字段,update函数中为可选字段,也可以表示为['*:M'],表示任何情况下都是必要字段(**默认**) |
| error_msg    | 字符串                                         | 错误提示信息,默认为'%(result)s',即validator返回的报错信息,用户可以固定字符串或使用带有%(result)s的模板字符串 |
| converter    | converter对象                                  | 数据转换器,当数据被校验后,可能需要转换为固定类型后才能进行编程处理,转换器可以为此提供自动转换,比如用户输入为'2018-01-01 01:01:01'字符串时间,程序需要为Datetime类型,则可以使用DateTimeConverter进行转换 |
| orm_required | 布尔值                                         | 控制此字段是否会被传递到数据库SQL中去                        |
| aliases      | 数组                                           | 字段的别名,比如接口升级后为保留前向兼容,老字段可以作为别名指向到新名称上 |
| nullable     | 布尔值                                         | 控制此字段是否可以为None,**默认False**                      |

CRUD使用方式:

```python
resource.User().create({'id': '1', 'name': 'test'})
resource.User().list()
resource.User().list({'name': 'test'})
resource.User().list({'name': {'ilike': 'na'}}, offset=0, limit=5)
resource.User().count()
resource.User().count({'name': 'test'})
resource.User().count({'name': {'ilike': 'na'}})
resource.User().get('1')
resource.User().update('1', {'name': 'test1'})
resource.User().delete('1')
resource.UserPhoneNum().get(('1', '10086'))
resource.UserPhoneNum().delete(('1', '10086'))
```

内部查询通过组装dict来实现过滤条件,filter在表达 == 或 in 列表时,可以直接使用一级字段即可,如
name等于test:{'name': 'test'}
id在1,2,3,4内:{'id': ['1', '2', '3', '4']}

更复杂的查询需要通过嵌套dict来实现[^ 5]:
- 简单组合:{'字段名称': {'过滤条件1': '值', '过滤条件2': '值'}}

- 简单\$or+组合查询:{'\$or': [{'字段名称': {'过滤条件': '值'}}, {'字段名称': {'过滤条件1': '值', '过滤条件2': '值'}}]}

- 简单\$and+组合查询:{'\$and': [{'字段名称': {'过滤条件': '值'}}, {'字段名称': {'过滤条件1': '值', '过滤条件2': '值'}}]}

- 复杂\$and+\$or+组合查询:
  {'\$and': [
  ​               {'\$or': [{'字段名称': '值'}, {'字段名称': {'过滤条件1': '值', '过滤条件2': '值'}}]}, 
  ​               {'字段名称': {'过滤条件1': '值', '过滤条件2': '值'}}
  ]}
  
- relationship复杂查询(>=v1.3.6):
  
  假定有User(用户),Article(文章),Comment(评论/留言)表,Article.owner引用User, Article.comments引用Comment,Comment.user引用User
  
  查询A用户发表的文章中,存在B用户的评论,且评论内容包含”你好“
  
  Article.list({'owner_id': 'user_a', 'comments': {'content': {'ilike': '你好', 'user': {'id': 'user_b'}}}})

| 过滤条件 | 值类型          | 含义                                                           |
| -------- | --------------- | -------------------------------------------------------------- |
| like      | string         | 模糊查询,包含条件                                          |
| ilike     | string         | 同上,不区分大小写                                             |
| starts    | string         | 模糊查询,以xxxx开头                                           |
| istarts   | string         | 同上,不区分大小写                                             |
| ends      | string         | 模糊查询,以xxxx结尾                                           |
| iends     | string         | 同上,不区分大小写                                             |
| in        | list           | 精确查询,条件在列表中                                         |
| nin       | list           | 精确查询,条件不在列表中                                       |
| eq        | 根据字段类型   | 等于                                                           |
| ne        | 根据字段类型   | 不等于                                                         |
| lt        | 根据字段类型   | 小于                                                           |
| lte       | 根据字段类型   | 小于等于                                                       |
| gt        | 根据字段类型   | 大于                                                           |
| gte       | 根据字段类型   | 大于等于                                                       |
| nlike     | string         | 模糊查询,不包含                                               |
| nilike    | string         | 同上,不区分大小写                                             |
| null      | 任意           | 是NULL,等同于{'eq': None},null主要提供HTTP API中使用                   |
| nnull     | 任意           | 不是NULL,等同于{'ne': None},nnull主要提供HTTP API中使用                  |
| hasany       | string/list[string] | *JSONB专用*   包含任意key,如['a','b', 'c'] hasany ['a','d'] |
| hasall       | string/list[string] | *JSONB专用*   包含所有key,如['a','b', 'c'] hasall ['a','c'] |
| within       | list/dict | *JSONB专用*   被指定json包含在内                             |
| nwithin      | list/dict | *JSONB专用*   不被指定json包含在内                           |
| include      | list/dict | *JSONB专用*   包含指定的json                                 |
| ninclude     | list/dict | *JSONB专用*   不包含指定的json                               |


过滤条件可以根据不同的数据类型生成不同的查询语句,varchar类型的in是 IN ('1', '2') , inet类型的in是<<=cidr

一般类型的eq是col='value',bool类型的eq是col is TRUE,详见talos.db.filter_wrapper

#### 业务api控制类

api的模块为:cms.apps.user.api

resource处理的是DB的CRUD操作,但往往业务类代码需要有复杂的处理逻辑,并且涉及多个resource类的相互操作,因此需要封装api层来处理此类逻辑,此处我们示例没有复杂逻辑,直接沿用定义即可

```python
User = resource.User
UserPhoneNum = resource.UserPhoneNum
```

#### Collection和Item Controller

Controller模块为:cms.apps.user.controller

Controller被设计分类为Collection和Item 2种,分别对应RESTFul的URL操作,我们先看一个常见的URL设计和操作

```bash
POST   /v1/users    创建用户
GET    /v1/users    查询用户列表
PATCH  /v1/users/1  更新用户1的信息
DELETE /v1/users/1  删除用户1的信息
GET    /v1/users/1  获取用户1的详情
```

根据当前的URL规律我们可以吧创建和查询列表作为一个封装(CollectionController),而更新,删除,获取详情作为一个封装(ItemController),而同样的,对于这样的标准操作,talos同样提供了魔法般的定义

```python
class CollectionUser(CollectionController):
    name = 'cms.users'
    resource = api.User

class ItemUser(ItemController):
    name = 'cms.user'
    resource = api.User
```

#### route路由映射

route模块为:cms.apps.user.route

提供了Controller后,我们还需要将其与URL路由进行映射才能调用,route模块中,必须有add_routes函数,注册app的时候会默认寻找这个函数来注册路由

```python
def add_routes(api):
    api.add_route('/v1/users', controller.CollectionUser())
    api.add_route('/v1/users/{rid}', controller.ItemUser())
```

#### 配置启动加载app

我们在引导开始时创建的项目配置文件存放在./etc中,所以我们的配置文件在./etc/cms.conf,修改

```javascript
...
"application": {
        "names": [
            "cms.apps.user"]
},
...
```

#### 启动调试或部署

在源码目录中有server包,其中simple_server是用于开发调试用,不建议在生产中使用

python simple_server.py

#### 测试API

启动后我们的服务已经可以对外输出啦!

那么我们的API到底提供了什么样的能力呢?我们以user作为示例展示

创建

```
POST /v1/users
Content-Type: application/json;charset=UTF-8
Host: 127.0.0.1:9002

{
    "id": "1",
    "name": "test"
}
```

查询列表

```
GET /v1/users
Host: 127.0.0.1:9002

{
    "count": 1,
    "data": [
        {
            "id": "1",
            "name": "test"
        }
    ]
}
```

关于查询列表,我们提供了强大的查询能力,可以满足大部分的查询场景

获取**列表(查询)的接口**可以使用Query参数过滤,使用过滤字段=xxx 或 字段__查询条件=xxx方式传递

- **过滤条件**

     eg.

     ```bash
     # 查询name字段等于abc
     name=abc
     # 查询name字段包含abc
     name__icontains=abc
     # 查询name字段在列表[a, b, c]值内
     name=a&name=b&name=c 
     # 或 
     name__in=a&name__in=b&name__in=c
     # 查询name字段在列表值内
     name[0]=a&name[1]=b&name[2]=c 
     # 或 
     name__in[0]=a&name__in[1]=b&name__in[2]=c
     ```

     同时支持全拼条件和缩写条件查询:


| 全拼条件     | 缩写条件 | 含义                                                         |
| ------------ | -------- | ------------------------------------------------------------ |
| N/A          |          | 精确查询,完全等于条件,如果多个此条件出现,则认为条件在列表中 |
| contains     | like     | 模糊查询,包含条件                                           |
| icontains    | ilike    | 同上,不区分大小写                                           |
| startswith   | starts   | 模糊查询,以xxxx开头                                         |
| istartswith  | istarts  | 同上,不区分大小写                                           |
| endswith     | ends     | 模糊查询,以xxxx结尾                                         |
| iendswith    | iends    | 同上,不区分大小写                                           |
| in           | in       | 精确查询,条件在列表中                                       |
| notin        | nin      | 精确查询,条件不在列表中                                     |
| equal        | eq       | 等于                                                         |
| notequal     | ne       | 不等于                                                       |
| less         | lt       | 小于                                                         |
| lessequal    | lte      | 小于等于                                                     |
| greater      | gt       | 大于                                                         |
| greaterequal | gte      | 大于等于                                                     |
| excludes     | nlike    | 模糊查询,不包含                                             |
| iexcludes    | nilike   | 同上,不区分大小写                                           |
| null         | null     | 是NULL                                                       |
| notnull      | nnull    | 不是NULL                                                     |
| hasany       | hasany   | *JSONB专用*   包含任意key,如['a','b', 'c'] hasany ['a','d'] |
| hasall       | hasall   | *JSONB专用*   包含所有key,如['a','b', 'c'] hasall ['a','c'] |
| within       | within   | *JSONB专用*   被指定json包含在内                             |
| nwithin      | nwithin  | *JSONB专用*   不被指定json包含在内                           |
| include      | include  | *JSONB专用*   包含指定的json                                 |
| ninclude     | ninclude | *JSONB专用*   不包含指定的json                               |



字段支持:普通column字段、relationship字段(single or list)、JSONB[^ 4]

假设有API对应如下表字段

```python
class User(Base, DictBase):
    __tablename__ = 'user'

    id = Column(String(36), primary_key=True)
    name = Column(String(36), nullable=False)
    department_id = Column(ForeignKey(u'department.id'), nullable=False)
    items = Column(JSONB, nullable=False)

    department = relationship(u'Department', lazy=False)
    addresses = relationship(u'Address', lazy=False, back_populates=u'user', uselist=True, viewonly=True)
    
class Address(Base, DictBase):
    __tablename__ = 'address'

    id = Column(String(36), primary_key=True)
    location = Column(String(36), nullable=False)
    user_id = Column(ForeignKey(u'user.id'), nullable=False)
    items = Column(JSONB, nullable=False)

    user = relationship(u'User', lazy=True)
    
class Department(Base, DictBase):
    __tablename__ = 'department'

    id = Column(String(36), primary_key=True)
    name = Column(String(36), nullable=False)
    user_id = Column(ForeignKey(u'user.id'), nullable=False)
```

可以这样构造过滤条件

/v1/users?name=小明

/v1/users?department.name=业务部

/v1/users?addresses.location__icontains=广东省

/v1/users?addresses.items.key__icontains=temp

/v1/users?items.0.age=60 # items = [{"age": 60, "sex": "male"}, {...}]

/v1/users?items.age=60 # items = {"age": 60, "sex": "male"}

> v1.2.0  起不支持的column或condition会触发ResourceBase._unsupported_filter(query, idx, name, op, value)函数,函数默认返回参数query以忽略未支持的过滤(兼容以前版本行为),用户可以自行重载函数以实现自定义行为
>
> v1.2.2  unsupported_filter会默认构造一个空查询集,即不支持的column或condition会致使返回空结果




- **偏移量与数量限制**

     查询返回列表时,通常需要指定偏移量以及数量限制

     eg. 

     ```bash
     __offset=10&__limit=20
     ```

     代表取偏移量10,限制20条结果

- **排序**

     排序对某些场景非常重要,可以免去客户端很多工作量

     ```bash
     __orders=name,-env_code
     ```

     多个字段排序以英文逗号间隔,默认递增,若字段前面有-减号则代表递减

     ```
       PS:我可以使用+name代表递增吗?
     
       可以,但是HTTP URL中+号实际上的空格的编码,如果传递__orders=+name,-env_code,在HTTP中实际等价于__orders=空格name,-env_code, 无符号默认递增,因此无需多传递一个+号,传递字段即可
     ```

- **字段选择**

     接口返回中,如果字段信息太多,会导致传输缓慢,并且需要客户端占用大量内存处理

     ```bash
     __fields=name,env_code
     ```

     可以指定返回需要的字段信息,或者干脆不指定,获取所有服务器支持的字段


### 进阶开发

#### 用户输入校验

用户输入的数据,不一定是完全正确的,每个数据都需要校验后才能进行存储和处理,在上面已经提到过使用ColumnValidator来进行数据校验,这里主要是解释详细的校验规则和行为

1. ColumnValidator被默认集成在ResourceBase中,所以会自动进行校验判断

2. 未定义_validate时,将不启用校验,信任所有输入数据

3. 未定义的字段在清洗阶段会被忽略

4. 校验的关键函数为ResourceBase.validate

   ```python
   @classmethod
   def validate(cls, data, situation, orm_required=False, validate=True, rule=None):
       """
       验证字段,并返回清洗后的数据
       
       * 当validate=False,不会对数据进行校验,仅返回ORM需要数据
       * 当validate=True,对数据进行校验,并根据orm_required返回全部/ORM数据
       
       :param data: 清洗前的数据
       :type data: dict
       :param situation: 当前场景
       :type situation: string
       :param orm_required: 是否ORM需要的数据(ORM即Model表定义的字段)
       :type orm_required: bool
       :param validate: 是否验证规则
       :type validate: bool
       :param rule: 规则配置
       :type rule: dict
       :returns: 返回清洗后的数据
       :rtype: dict
       """
   ```

   *validate_on为什么是填写:create:M或者update:M,因为validate按照函数名进行场景判定,在ResourceBase.create函数中,默认将situation绑定在当前函数,即 'create',update同理,而M代表必选,O代表可选*

5. 当前快速校验规则rule_type不能满足时,请使用Validator对象,内置Validator对象不能满足需求时,可以定制自己的Validator,Validator的定义需要满足2点:

   从NullValidator中继承

   重写validate函数,函数接受一个参数,并且返回True作为通过校验,返回错误字符串代表校验失败

6. Converter同上

#### 多数据库支持 [^ 7]

默认情况下,项目只会生成一个数据库连接池:对应配置项CONF.db.xxxx,若需要多个数据库连接池,则需要手动指定配置文件

```
"dbs": {
    "read_only": {
        "connection": "sqlite:///tests/a.sqlite3"
    },
    "other_cluster": {
        "connection": "sqlite:///tests/b.sqlite3"
    }
},
```

使用方式也简单,如下,生效优先级为:实例化参数 > 类属性orm_pool > defaultPool

```python
# 1. 在类属性中指定 
class Users(ResourceBase):
    orm_meta = models.Users
    orm_pool = pool.POOLS.read_only
    
# 2. 实例化时指定
Users(dbpool=pool.POOLS.readonly)

# 3. 若都不指定,默认使用defaultPool,即CONF.db配置的连接池
```




#### DB Hook操作

##### 简单hooks

在db创建一个记录时,假设希望id是自动生成的UUID,通常这意味着我们不得不重写create函数:

```python
class User(ResourceBase):
    orm_meta = models.User
    _primary_keys = 'id'
    
    def create(self, resource, validate=True, detail=True):
        resource['id'] = uuid.uuid4().hex
        super(User, self).create(resource, validate=validate, detail=validate)
```

这样的操作对于我们而言是很笨重的,甚至create的实现比较复杂,让我们不希望到create里面去加这些不是那么关键的代码,对于这些操作,talos分成了2种场景,_before_create, _addtional_create,根据名称我们能知道,它们分别代表

create执行开始前:常用于一些数据的自动填充

create执行后但未提交:常用于强事务控制的操作,可以使用同一个事务进行操作以便一起提交或回滚

同理还有update,delete

同样的list和count都有_addtional_xxxx钩子

##### 动态hooks

以上的hooks都是类成员函数代码定义的,当使用者想要临时增加一个hook的时候呢,或者根据某个条件判断是否使用一个hook时,我们需要一种更动态的hook来支持,目前只有list和count支持此类hooks

list,count的hook的函数定义为:function(query, filters),需要return 处理后的query

eg. self.list(hooks=[lambda q,f: return q])

##### 自定义query

在更复杂的场景下我们封装的操作函数可能无法达到目的,此时可以使用底层的SQLAlchemy Query对象来进行处理,比如在PG中INET类型的比较操作:

一个场景:我们不希望用户新增的子网信息与现有子网重叠

```python
query = self._get_query(session)
query = query.filter(self.orm_meta.cidr.op(">>")(
    subnet['cidr']) | self.orm_meta.cidr.op("<<")(subnet['cidr']))
if query.one_or_none():
    raise ConflictError()
```

#### 会话重用和事务控制

在talos中,每个ResourceBase对象都可以申请会话和事务,而且可以接受一个已有的会话和事务对象,在使用完毕后talos会自动帮助你进行回滚/提交/关闭,这得益与python的with子句

```python
u = User()
with u.transaction() as session:
    u.update(...)
    # 事务重用, 可以查询和变更操作, with子句结束会自动提交,异常会自动回滚
    UserPhone(transaction=session).delete(...)
    UserPhone(transaction=session).list(...)
with u.get_session() as session:
    # 会话重用, 可以查询
    UserPhone(session=session).list(...)
```

#### 缓存

##### 配置和使用

默认配置为进程内存,超时60秒

```python
'cache': {
        'type': 'dogpile.cache.memory',
        'expiration_time': 60
}
```

缓存后端支持取决于dogpile模块,可以支持常见的memcache,redis等

如:redis

```python
"cache": {
        "type": "dogpile.cache.redis",
        "expiration_time": 6,
        "arguments": {
            "host": "127.0.0.1",
            "password": "football",
            "port": 1234,
            "db": 0,
            "redis_expiration_time": 60,
            "distributed_lock": true
        }
    }
```

使用方式

```python
from talos.common import cache

cache.get(key, exipres=None)
cache.set(key, value)
cache.validate(value)
cache.get_or_create(key, creator, expires=None)
cache.delete(key)
```



#### 异步任务

##### 定义异步任务

> talos >=1.3.0 send_callback函数,移除了timeout,增加了request_context,为requests请求参数的options的字典,eg.{'timeout': 3}

> talos >=1.3.0 回调函数参数,移除了request和response的强制参数定义,保留data和url模板强制参数,如果callback(with_request=True),则回调函数需定义如下,with_response同理
>
> @callback('/add/{x}/{y}', with_request=True):
>
> def add(data, x, y, request):
>
> ​    pass

> talos >=1.3.0 被callback装饰的回调函数,均支持本地调用/快速远程调用/send_callback调用
>
> talos <1.3.0支持本地调用/send_callback调用
>
>     本地调用:
>     add(data, x, y),可以作为普通本地函数调用(注:客户端运行)
>        
>     send_callback远程调用方式(x,y参数必须用kwargs形式传参):
>     send_callback(None, add, data, x=1, y=7)
>        
>     快速远程调用:
>     支持设置context,baseurl进行调用,context为requests库的额外参数,比如headers,timeout,verify等,baseurl默认为配置项的public_endpoint(x,y参数必须用kwargs形式传参)
>        
>     test.remote({'val': '123'}, x=1, y=7)
>     test.context(timeout=10, params={'search': 'me'}).remote({'val': '123'}, x=1, y=7)
>     test.context(timeout=10).baseurl('http://clusterip.of.app.com').remote({'val': '123'}, x=1, y=7)

建立workers.app_name.tasks.py用于编写远程任务
建立workers.app_name.callback.py用于编写远程调用
task.py任务示例

```python
from talos.common import celery
from talos.common import async_helper
from cms.workers.app_name import callback
@celery.app.task
def add(data, task_id):
    result = {'result': data['x'] + data['y']}

    # 这里还可以通知其他附加任务,当需要本次的一些计算结果来启动二次任务时使用
    # 接受参数:task调用函数路径 & 函数命名参数(dict)
    # async_helper.send_task('cms.workers.app_name.tasks.other_task', kwargs={'result': result, 'task_id': task_id})

   # 异步任务中默认不启用数据库连接,因此需要使用远程调用callback方式进行数据读取和回写
   # 如果想要使用db功能,需要修改cms.server.celery_worker文件的代码,移除 # base.initialize_db()的注释符号

   # send callback的参数必须与callback函数参数匹配(request,response除外)
   # url_base为callback实际运行的服务端api地址,eg: http://127.0.0.1:9000
   # update_task函数接受data和task_id参数,其中task_id必须为kwargs形式传参
   # async_helper.send_callback(url_base, callback.update_task,
   #                             data,
   #                            task_id=task_id)
   # remote_result 对应数据为update_task返回的 res_after
   remote_result = callback.update_task.remote(result, task_id=task_id)
   # 此处是异步回调结果,不需要服务器等待或者轮询,worker会主动发送进度或者结果,可以不return
   # 如果想要使用return方式,则按照正常celery流程编写代码
   return result
```

callback.py回调示例 (callback不应理解为异步任务的回调函数,泛指talos的通用rpc远程调用,只是目前框架内主要使用方是异步任务)
```python
from talos.common import async_helper
# data是强制参数,task_id为url强制参数(如果url没有参数,则函数也无需task_id)
# task_id为url强制参数,默认类型是字符串(比如/callback/add/{x}/{y},函数内直接执行x+y结果会是字符串拼接,因为由于此参数从url中提取,所以默认类型为str,需要特别注意)
@async_helper.callback('/callback/add/{task_id}')
def update_task(data, task_id):
    # 远程调用真正执行方在api server服务,因此默认可以使用数据库操作
    res_before,res_after = task_db_api().update(task_id, data)
    # 函数可返回可json化的数据,并返回到调用客户端去
    return res_after
```

route中注册回调函数,否则无法找到此远程调用
```python
from talos.common import async_helper
from project_name.workers.app_name import callback

def add_route(api):
    async_helper.add_callback_route(api, callback.callback_add)
```

启动worker
  celery -A cms.server.celery_worker worker --autoscale=50,4 --loglevel=DEBUG -Q your_queue_name

调用
  add.delay('id', 1, 1)
  会有任务发送到worker中,然后woker会启动一个other_task任务,并回调url将结果发送会服务端

  (如果API模块有统一权限校验,请注意放行)



##### 异步任务配置

依赖:
​    库:
​        celery

​    配置:

```
{
        ...
        "celery": {
            "worker_concurrency": 8,
            "broker_url": "pyamqp://guest@127.0.0.1//",
            "result_backend": "redis://127.0.0.1",
            "imports": [
                "project_name.workers.app_name.tasks"
            ],
            "task_serializer": "json",
            "result_serializer": "json",
            "accept_content": ["json"],
            "worker_prefetch_multiplier": 1,
            "task_routes": {
                "project_name.workers.*": {"queue": "your_queue_name",
                                        "exchange": "your_exchange_name",
                                        "routing_key": "your_routing_name"}
            }
        },
        "worker": {
            "callback": {
                "strict_client": true,
                "allow_hosts": ["127.0.0.1"]
            }
        }
}
```





#### 定时任务[^ 2]

talos中你可以使用原生celery的定时任务机制,也可以使用talos中提供的扩展定时任务(TScheduler),扩展的定时任务可以在5s(可通过beat_max_loop_interval来修改这个时间)内发现定时任务的变化并刷新调度,从而提供动态的定时任务,而定时任务的来源可以从配置文件,也可以通过自定义的函数中动态提供

> 原生celery的scheduler是不支持动态定时任务的

> 使用原生celery定时任务因为talos配置项为json数据而无法提供复杂类型的schedule,当然也可以使用add_periodic_task来解决,但会降低我们使用的便利性
>
> 这些问题在talos扩展定时任务中得以解决

##### 静态配置定时任务:

使用最原始的celery定时任务配置,最快捷的定时任务例子[^ 3]:

```json
    "celery": {
        "worker_concurrency": 8,
        "broker_url": "pyamqp://test:test@127.0.0.1//",
        ...
        "beat_schedule": {
            "test_every_5s": {
                "task": "cms.workers.periodic.tasks.test_add",
                "schedule": 5,
                "args": [3,6] 
            }
        }
```

启动beat: celery -A cms.server.celery_worker beat --loglevel=DEBUG

启动worker:celery -A cms.server.celery_worker worker --loglevel=DEBUG -Q cms-dev-queue

可以看到每5s,beat会发送一个任务,worker会接收此任务进行处理,从而形成定时任务

使用过原生celery的人可能看出这里存在的问题:crontab是对象,json配置是无法传递,只能配置简单的间隔任务,确实,缺省情况下由于配置文件格式的原因无法提供更高级的定时任务配置,所以talos提供了自定义的Scheduler:TScheduler,这个调度器可以从配置文件中解析interval、crontab类型的定时任务,从而覆盖更广泛的需求,而使用也非常简单:

```json
"celery": {
    "worker_concurrency": 8,
    "broker_url": "pyamqp://test:test@127.0.0.1//",
    ...
    "beat_schedule": {
        "test_every_5s": {
            "task": "cms.workers.periodic.tasks.test_add",
            "schedule": 5,
            "args": [3,6] 
        },
        "test_every_123s": {
            "type": "interval",
            "task": "cms.workers.periodic.tasks.test_add",
            "schedule": "12.3",
            "args": [3,6] 
        },
        "test_crontab_simple": {
            "type": "crontab",
            "task": "cms.workers.periodic.tasks.test_add",
            "schedule": "*/1",
            "args": [3,6] 
        },
        "test_crontab": {
            "type": "crontab",
            "task": "cms.workers.periodic.tasks.test_add",
            "schedule": "1,13,30-45,50-59/2 *1 * * *",
            "args": [3,6] 
        }
    }
```
依然是在配置文件中定义,多了一个type参数,用于帮助调度器解析定时任务,此外还需要指定使用talos的TScheduler调度器,比如配置中指定:

```
"celery": {
    "worker_concurrency": 8,
    "broker_url": "pyamqp://test:test@127.0.0.1//",
    ...
    "beat_schedule": {...}
    "beat_scheduler": "talos.common.scheduler:TScheduler"
```

或者命令行启动时指定:

启动beat: celery -A cms.server.celery_worker beat --loglevel=DEBUG -S talos.common.scheduler:TScheduler 

启动worker:celery -A cms.server.celery_worker worker --loglevel=DEBUG -Q cms-dev-queue

除了type,TScheduler的任务还提供了很多其他的扩展属性,以下是属性以及其描述

```
name:           string, 唯一名称
task:           string, 任务模块函数
[description]:  string, 备注信息
[type]:         string, interval 或 crontab, 默认 interval
schedule:       string/int/float/schedule eg. 1.0,'5.1', '10 *' , '*/10 * * * *' 
args:           tuple/list, 参数
kwargs:         dict, 命名参数
[priority]:     int, 优先级, 默认5
[expires]:      int, 单位为秒,当任务产生后,多久还没被执行会认为超时
[enabled]:      bool, True/False, 默认True
[max_calls]:    None/int, 最大调度次数, 默认None无限制
[last_updated]: Datetime, 任务最后更新时间,常用于判断是否有定时任务需要更新
```



##### 动态配置定时任务:

TScheduler的动态任务仅限用户自定义的所有schedules
所有定时任务 = 配置文件任务 + add_periodic_task任务 + hooks任务,hooks任务可以通过相同name来覆盖已存在配置中的任务,否则相互独立

- 使用TScheduler预留的hooks进行动态定时任务配置(推荐方式):

  TScheduler中预留了2个hooks:talos_on_user_schedules_changed/talos_on_user_schedules

  **talos_on_user_schedules_changed**钩子用于判断是否需要更新定时器,钩子被执行的最小间隔是beat_max_loop_interval(如不设置默认为5s)

  钩子定义为callable(scheduler),返回值是True/False

  **talos_on_user_schedules**钩子用于提供新的定时器字典数据

  钩子定义为callable(scheduler),返回值是字典,全量的自定义动态定时器

  我们来尝试提供一个,每过13秒自动生成一个全新定时器的代码

  以下是cms.workers.periodic.hooks.py的文件内容

  ```python
  import datetime
  from datetime import timedelta
  import random
  
  # talos_on_user_schedules_changed, 用于判断是否需要更新定时器
  # 默认每5s调用一次
  class ChangeDetection(object):
      '''
      等价于函数,只是此处我们需要保留_last_modify属性所以用类来定义callable
      def ChangeDetection(scheduler):
          ...do something...
      '''
      def __init__(self, scheduler):
          self._last_modify = self.now()
      def now(self):
          return datetime.datetime.now()
      def __call__(self, scheduler):
          now = self.now()
          # 每过13秒定义定时器有更新
          if now - self._last_modify >= timedelta(seconds=13):
              self._last_modify = now
              return True
          return False
  
  # talos_on_user_schedules, 用于提供新的定时器字典数据
  # 在talos_on_user_schedules_changed hooks返回True后被调用
  class Schedules(object):
      '''
      等价于函数
      def Schedules(scheduler):
          ...do something...
      '''
      def __init__(self, scheduler):
          pass
      def __call__(self, scheduler):
          interval = random.randint(1,10)
          name = 'dynamic_every_%s s' % interval
          # 生成一个纯随机的定时任务
          return {name: {'task': 'cms.workers.periodic.tasks.test_add', 'schedule': interval, 'args': (1,3)}}
  ```

  配置文件如下:

  ```json
      "celery": {
          ...
          "beat_schedule": {
              "every_5s_max_call_2_times": {
                  "task": "cms.workers.periodic.tasks.test_add",
                  "schedule": "5",
                  "max_calls": 2,
                  "enabled": true,
                  "args": [1, 3]
              }
          },
          "talos_on_user_schedules_changed":[
              "cms.workers.periodic.hooks:ChangeDetection"],
          "talos_on_user_schedules": [
              "cms.workers.periodic.hooks:Schedules"]
      },
  ```

  得到的结果是,一个每5s,最多调度2次的定时任务;一个每>=13s自动生成的随机定时任务

- 使用官方的setup_periodic_tasks进行动态配置

  见celery文档

  截止2018.11.13 celery 4.2.0在定时任务中依然存在问题,使用官方建议的on_after_configure动态配置定时器时,定时任务不会被触发:[GitHub Issue 3589](https://github.com/celery/celery/issues/3589)

  ```
  @celery.app.on_after_configure.connect
  def setup_periodic_tasks(sender, **kwargs):
      sender.add_periodic_task(3.0, test.s('add every 3s by add_periodic_task'), name='add every 3s by add_periodic_task')
  
  @celery.app.task
  def test(arg):
      print(arg)
  ```

而测试以下代码有效,可以使用以下方法:

```
@celery.app.on_after_finalize.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(3.0, test.s('add every 3s by add_periodic_task'), name='add every 3s by add_periodic_task')

@celery.app.task
def test(arg):
    print(arg)
```

#### 频率限制

##### controller & 中间件 频率限制

主要用于http接口频率限制

    基本使用步骤:
    
    - 在controller上配置装饰器
    - 将Limiter配置到启动中间件
    
    装饰器通过管理映射关系表LIMITEDS,LIMITEDS_EXEMPT来定位用户设置的类实例->频率限制器关系,
    频率限制器是实例级别的,意味着每个实例都使用自己的频率限制器
    
    频率限制器有7个主要参数:频率设置,关键限制参数,限制范围,是否对独立方法进行不同限制, 算法,错误提示信息, hit函数
    
    :param limit_value: 频率设置:格式[count] [per|/] [n (optional)][second|minute|hour|day|month|year]
    :param key_function: 关键限制参数:默认为IP地址(支持X-Forwarded-For),自定义函数:def key_func(req) -> string
    :param scope: 限制范围空间:默认python类完整路径,自定义函数def scope_func(request) -> string
    :param per_method: 指定是否根据每个HTTP方法区分频率限制,默认True
    :param strategy: 算法:支持fixed-window、fixed-window-elastic-expiry、moving-window
    :param message: 错误提示信息:错误提示信息可接受3个格式化(limit,remaining,reset)内容
    :param hit_func: 函数定义为def hit(controller, request) -> bool,为True时则触发频率限制器hit,否则忽略

> PS:真正的频率限制范围 = 关键限制参数(默认IP地址) + 限制范围(默认python类完整路径) + 方法名(如果区分独立方法),当此频率范围被命中后才会触发频率限制





###### 静态频率限制(配置/代码)

**controller级的频率限制**

```python
# coding=utf-8

import falcon
from talos.common import decorators as deco
from talos.common import limitwrapper

# 快速自定义一个简单支持GET、POST请求的Controller
# add_route('/things', ThingsController())

@deco.limit('1/second')
class ThingsController(object):
    def on_get(self, req, resp):
        """Handles GET requests, using 1/second limit"""
        resp.body = ('It works!')
    def on_post(self, req, resp):
        """Handles POST requests, using global limit(if any)"""
        resp.body = ('It works!')
```

###### 全局级的频率限制

```json
{
    "rate_limit": {
        "enabled": true,
        "storage_url": "memory://",
        "strategy": "fixed-window",
        "global_limits": "5/second",
        "per_method": true,
        "header_reset": "X-RateLimit-Reset",
        "header_remaining": "X-RateLimit-Remaining",
        "header_limit": "X-RateLimit-Limit"
    }
}
```

###### 基于中间件动态频率限制

以上的频率限制都是预定义的,无法根据具体参数进行动态的更改,而通过重写中间件的get_extra_limits函数,我们可以获得动态追加频率限制的能力

```python
class MyLimiter(limiter.Limiter):
    def __init__(self, *args, **kwargs):
        super(MyLimiter, self).__init__(*args, **kwargs)
        self.mylimits = {'cms.apps.test1': [wrapper.LimitWrapper('2/second')]}
    def get_extra_limits(self, request, resource, params):
        if request.method.lower() == 'post':
            return self.mylimits['cms.apps.test1']

```

频率限制默认被加载在了系统的中间件中,如果不希望重复定义中间件,可以在cms.server.wsgi_server中修改项目源代码:

```python
application = base.initialize_server('cms',
                                     ...
                                     middlewares=[
                                         globalvars.GlobalVars(),
                                         MyLimiter(),
                                         json_translator.JSONTranslator()],
                                     override_middlewares=True)
```

##### 函数级频率限制

```python
from talos.common import decorators as deco

@deco.flimit('1/second')
def test():
    pass
```



    用于装饰一个函数表示其受限于此调用频率
    当装饰类成员函数时,频率限制范围是类级别的,意味着类的不同实例共享相同的频率限制,
    如果需要实例级隔离的频率限制,需要手动指定key_func,并使用返回实例标识作为限制参数
    
    :param limit_value: 频率设置:格式[count] [per|/] [n (optional)][second|minute|hour|day|month|year]
    :param scope: 限制范围空间:默认python类/函数完整路径 or 自定义字符串.
    :param key_func: 关键限制参数:默认为空字符串,自定义函数:def key_func(*args, **kwargs) -> string
    :param strategy: 算法:支持fixed-window、fixed-window-elastic-expiry、moving-window
    :param message: 错误提示信息:错误提示信息可接受3个格式化(limit,remaining,reset)内容
    :param storage: 频率限制后端存储数据,如: memory://, redis://:pass@localhost:6379
    :param hit_func: 函数定义为def hit(result) -> bool(参数为用户函数执行结果,若delay_hit=False,则参数为None),为True时则触发频率限制器hit,否则忽略
    :param delay_hit: 默认在函数执行前测试频率hit(False),可以设置为True将频率测试hit放置在函数执行后,搭配hit_func
                       使用,可以获取到函数执行结果来控制是否执行hit
关于函数频率限制模块更多用例,请见单元测试tests.test_limit_func

#### 数据库版本管理

修改models.py为最终目标表模型,运行命令:

alembic revision --autogenerate -m "add table: xxxxx"

备注不支持中文, autogenerate用于生成upgrade,downgrade函数内容,生成后需检查升级降级函数是否正确

升级:alembic upgrade head

降级:alembic downgrade base

head指最新版本,base指最原始版本即models第一个version,更多升级降级方式如下:

- alembic upgrade +2 升级2个版本

- alembic downgrade -1 回退一个版本

- alembic upgrade ae10+2 升级到ae1027a6acf+2个版本

```python
# alembic 脚本内手动执行sql语句
op.execute('raw sql ...')
```




#### 单元测试

talos生成的项目预置了一些依赖要求,可以更便捷的使用pytest进行单元测试,如需了解更详细的单元测试编写指导,请查看pytest文档

> python setup.py test

可以简单从命令行输出中查看结果,或者从unit_test_report.html查看单元测试报告,从htmlcov/index.html中查看覆盖测试报告结果

示例可以从talos源码的tests文件夹中查看

```bash
$ tree tests
tests
├── __init__.py
├── models.py
├── test_db_filters.py
├── unittest.conf
├── unittest.sqlite3
└── ...

```

单元测试文件以test_xxxxxx.py作为命名

## Sphinx注释文档

Sphinx的注释格式这里不再赘述,可以参考网上文档教程,talos内部使用的注释文档格式如下:

```
    """
    函数注释文档

    :param value: 参数描述
    :type value: 参数类型
    :returns: 返回值描述
    :rtype: `bytes`/`str` 返回值类型
    """
```



- 安装sphinx

- 在工程目录下运行:

  sphinx-quickstart docs

  - root path for the documentation [.]: docs
  - Project name: cms
  - Author name(s): Roy
  - Project version []: 1.0.0
  - Project language [en]: zh_cn
  - autodoc: automatically insert docstrings from modules (y/n) [n]: y

- 可选的风格主题,推荐sphinx_rtd_theme,需要pip install sphinx_rtd_theme

- 修改docs/conf.py

  ```python
  # import os
  # import sys
  # sys.path.insert(0, os.path.abspath('.'))
  import os
  import sys
  sys.path.insert(0, os.path.abspath('..'))
  
  import sphinx_rtd_theme
  html_theme = "sphinx_rtd_theme"
  html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
  ```

- 生成apidoc sphinx-apidoc -o docs/ ./cms

- 生成html:

  - cd docs
  - make.bat html
  - 打开docs/_build/html/index.html

## 国际化i18n

同样以cms项目作为例子

### 提取待翻译

```bash
# 需要翻译项目的语言
find /usr/lib/python2.7/site-packages/cms/ -name "*.py" >POTFILES.in
# 需要翻译talos的语言
find /usr/lib/python2.7/site-packages/talos/ -name "*.py" >>POTFILES.in
# 提取为cms.po
xgettext --default-domain=cms --add-comments --keyword=_ --keyword=N_ --files-from=POTFILES.in --from-code=UTF8
```



### 合并已翻译

```bash
msgmerge cms-old.po cms.po -o cms.po
```



### 翻译

可以使用如Poedit的工具帮助翻译

(略)

### 编译发布

Windows:使用Poedit工具,则点击保存即可生成cms.mo文件

Linux:msgfmt --output-file=cms.mo cms.po

将mo文件发布到

/etc/{\$your_project}/locale/{\$lang}/LC_MESSAGES/

{\$lang}即配置项中的language



## 日志配置

### 配置指引

全局日志配置为log对象,默认使用WatchedFileHandler进行日志处理,而文件则使用path配置,如果希望全局日志中使用自定义的Handler,则path参数是可选的

全局日志通常可以解决大部分场景,但有时候,我们希望不同模块日志输出到不同文件中,可以使用:loggers,子日志配置器,其参数可完全参考log全局日志参数(除gunicorn_access,gunicorn_error),通过name指定捕获模块,并可以设置propagate拦截不传递到全局日志中

不论全局或子级日志配置,都可以指定使用其他handler,并搭配handler_args自定义日志使用方式,指定的方式为:package.module:ClassName,默认时我们使用WatchedFileHandler,因为日志通常需要rotate,我们希望日志模块可以被无缝切割轮转而不影响应用,所以这也是我们没有将内置Handler指定为RotatingFileHandler的原因,用户需要自己使用操作系统提供的logrotate能力进行配置。

以下是一个常用的日志配置,全局日志记录到server.log,而模块cms.apps.filetransfer日志则单独记录到transfer.log文件,相互不影响

```json
"log": {
    "gunicorn_access": "./access.log",
    "gunicorn_error": "./error.log",
    "path": "./server.log",
    "level": "INFO",
    "format_string": "%(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s:%(lineno)d [-] %(message)s",
    "date_format_string": "%Y-%m-%d %H:%M:%S",
    "loggers": [
        {
            "name": "cms.apps.filetransfer",
         	"level": "INFO",
         	"path": "./transfer.log",
            "propagate": false
        }
    ]
}
```



其详细参数说明如下:

| 路径               | 类型   | 描述                                                         | 默认值                                                       |
| ------------------ | ------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| gunicorn_access    | string | 使用gunicorn时,access日志路径                               | ./access.log                                                 |
| gunicorn_error     | string | 使用gunicorn时,error日志路径                                | ./error.log                                                  |
| log_console        | bool   | 是否将本日志重定向到标准输出                                 | True                                                         |
| path               | string | 日志路径,默认使用WatchedFileHandler,当指定handler时此项无效 | ./server.log                                                 |
| level              | string | 日志级别(ERROR,WARNING,INFO,DEBUG)                        | INFO                                                         |
| handler            | string | 自定义的Logger类,eg: logging.handlers:SysLogHandler,定义此项后会优先使用并忽略默认的log.path参数,需要使用handler_args进行日志初始化参数定义 |                                                              |
| handler_args       | list   | 自定义的Logger类的初始化参数,eg: []                         | []                                                           |
| format_string      | string | 日志字段配置                                                 | %(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s:%(lineno)d [-] %(message)s |
| date_format_string | string | 日志时间格式                                                 | %Y-%m-%d %H:%M:%S                                            |
| name               | string | 全局log中无此参数,仅用于loggers子日志配置器上,表示捕获的日志模块路径 |                                                              |
| propagate          | bool   | 全局log中无此参数,仅用于loggers子日志配置器上,表示日志是否传递到上一级日志输出 | True                                                         |



## 工具库

### 带宽限速

linux系统端口带宽限速:talos.common.bandwidth_limiter:BandWidthLimiter

传输流带宽限速:未提供

### 格式转换

#### 表格导出

csv:talos.common.exporter:export_csv

xlsx:未提供

#### dict转xml

talos.core.xmlutils:toxml

xmlutils作为core模块的一份子,很重要的一点是:必须保证足够的扩展性,其提供了自定义类型的转换钩子

```python
test = {'a': 1, 'b': 1.2340932, 'c': True, 'd': None, 'e': 'hello <world />', 'f': {
    'k': 'v', 'm': 'n'}, 'g': [1, '2', False, None, {'k': 'v', 'm': [1, 2, 3]}],
    'h': et.Element('root')}
toxml(test, 
      attr_type=True,
      hooks={'etree': {'render': lambda x: x.tag, 'hit': lambda x: isinstance(x, et.Element)}})
```

输出结果:

```xml

```

默认情况下,所有未定义的类型,都会被default_render(实际上就是str() )进行转换渲染

hooks中定义的etree是作为xml的节点type属性输出,hit函数是用于判定定义的类型归属,render用于提取对象内容



### 登录认证

Ldap认证:talos.common.ldap_util:Ldap

授权校验:talos.core.acl:Registry

acl模块提供了扩展于RBAC的授权模式:policy概念对应角色(支持角色继承),allow/deny对应一个权限规则,传统RBAC将角色与用户绑定即完成授权,但acl模块中,我们认为权限不是固定的,在不同的场景中,用户可以有不同的角色,来执行不同的动作,我们将场景定义为template(场景模板),假定某用户在操作广州的资源时,可以获得最大的admin权限,而操作上海的资源时只有readonly角色权限

```python
access = Registry()
access.add_policy('readonly')
access.add_policy('manage', parents=('readonly',))
access.add_policy('admin', parents=('manage',))
access.allow('readonly', 'resource.list')
access.allow('manage', 'resource.create')
access.allow('manage', 'resource.update')
access.allow('manage', 'resource.delete')
access.allow('admin', 'auth.manage')
# bind user1 with policies: (GZ, admin), (SH, readonly)
# get current region: SH
assert access.is_allowed([('GZ', 'admin'), ('SH', 'readonly')], 'SH', 'resource.create') is not True
# bind user2 with policies: (*, manage)
# get current region: SH
assert access.is_allowed([('*', 'manage')], 'SH', 'resource.create') is True
```

如上所示template(场景模板)是可以模糊匹配的,其默认匹配规则如下(匹配函数可以通过Registry更改):

| Pattern  | Meaning                            |
| -------- | ---------------------------------- |
| `*`      | matches everything                 |
| `?`      | matches any single character       |
| `[seq]`  | matches any character in *seq*     |
| `[!seq]` | matches any character not in *seq* |

如此一来我们便可以便捷实现一个基于场景的角色权限校验。

### SMTP邮件发送

talos.common.mailer:Mailer

### 实用小函数

talos.core.utils

## 配置项

talos提供了一个类字典的属性访问配置类
1. 当属性是标准变量命名且非预留函数名时,可直接a.b.c方式访问
2. 否则可以使用a['b-1'].c访问(item方式访问时会返回Config对象)
3. 当属性值刚好Config已存在函数相等时,将进行函数调用而非属性访问!!!
   保留函数名如下:set_options,from_files,iterkeys,itervalues,iteritems,keys,values,items,get,to_dict,_opts,python魔法函数

比如{
​        "my_config": {"from_files": {"a": {"b": False}}}
​    }
无法通过CONF.my_config.from_files来访问属性,需要稍作转换:CONF.my_config['from_files'].a.b 如此来获取,talos会在项目启动时给予提示,请您关注[^ 8]

### 预渲染项

talos中预置了很多控制程序行为的配置项,可以允许用户进行相关的配置:全局配置、启动服务配置、日志配置、数据库连接配置、缓存配置、频率限制配置、异步和回调配置

此外,还提供了配置项variables拦截预渲染能力[^ 6], 用户可以定义拦截某些配置项,并对其进行修改/更新(常用于密码解密),然后对其他配置项的变量进行渲染替换,使用方式如下:

```json
{
    "variables": {"db_password": "MTIzNDU2", "other_password": "..."}
    "db": {"connection": "mysql://test:${db_password}@127.0.0.1:1234/db01"}
}
```

如上,variables中定义了定义了db_password变量(**必须在variables中定义变量**),并再db.connection进行变量使用(**除variables以外其他配置项均可使用\${db_password}变量进行待渲染**)

在您自己的项目的server.wsgi_server 以及 server.celery_worker代码开始位置使用如下拦截:

```python
import base64
from talos.core import config

@config.intercept('db_password', 'other_password')
def get_password(value, origin_value):
    '''value为上一个拦截器处理后的值(若此函数为第一个拦截器,等价于origin_value)
       origin_value为原始配置文件的值
       没有拦截的变量talos将自动使用原始值,因此定义一个拦截器是很关键的
       函数处理后要求必须返回一个值
    '''
    # 演示使用不安全的base64,请使用你认为安全的算法进行处理
    return base64.b64decode(origin_value)


```

> 为什么要在server.wsgi_server 以及 server.celery_worker代码开始位置拦截?
>
> 因为配置项为预渲染,即程序启动时,就将配置项正确渲染到变量中,以便用户代码能取到正确的配置值,放到其他位置会出现部分代码得到处理前值,部分代码得到处理后值,结果将无法保证一致,因此server.wsgi_server 以及 server.celery_worker代码开始位置设置拦截是非常关键的



### 配置项

| 路径                                   | 类型   | 描述                                                         | 默认值                                                       |
| -------------------------------------- | ------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| host                                   | string | 主机名                                                       | 当前主机名                                                   |
| language                               | string | 系统语言翻译                                                 | en                                                           |
| locale_app                             | string | 国际化locale应用名称                                         | 当前项目名                                                   |
| locale_path                            | string | 国际化locale文件路径                                         | ./etc/locale                                                 |
| variables                              | dict   | 可供拦截预渲染的变量名及其值                                 | {}                                                           |
| controller.list_size_limit_enabled     | bool   | 是否启用全局列表大小限制                                     | False                                                        |
| controller.list_size_limit             | int    | 全局列表数据大小,如果没有设置,则默认返回全部,如果用户传入limit参数,则以用户参数为准 | None                                                         |
| controller.criteria_key.offset         | string | controller接受用户的offset参数的关键key值                    | __offset                                                     |
| controller.criteria_key.limit          | string | controller接受用户的limit参数的关键key值                     | __limit                                                      |
| controller.criteria_key.orders         | string | controller接受用户的orders参数的关键key值                    | __orders                                                     |
| controller.criteria_key.fields         | string | controller接受用户的fields参数的关键key值                    | __fields                                                     |
| override_defalut_middlewares           | bool   | 覆盖系统默认加载的中间件                                     | Flase                                                        |
| server                                 | dict   | 服务监听配置项                                               |                                                              |
| server.bind                            | string | 监听地址                                                     | 0.0.0.0                                                      |
| server.port                            | int    | 监听端口                                                     | 9001                                                         |
| server.backlog                         | int    | 监听最大队列数                                               | 2048                                                         |
| log                                    | dict   | 日志配置项                                                   |                                                              |
| log.log_console                        | bool   | 是否将日志重定向到标准输出                                   | True                                                         |
| log.gunicorn_access                    | string | gunicorn的access日志路径                                     | ./access.log                                                 |
| log.gunicorn_error                     | string | gunicorn的error日志路径                                      | ./error.log                                                  |
| log.path                               | string | 全局日志路径,默认使用WatchedFileHandler,当指定handler时此项无效 | ./server.log                                                 |
| log.level                              | string | 日志级别                                                     | INFO                                                         |
| log.handler[^ 7]                       | string | 自定义的Logger类,eg: logging.handlers:SysLogHandler,定义此项后会优先使用并忽略默认的log.path |                                                              |
| log.handler_args[^ 7]                  | list   | 自定义的Logger类的初始化参数,eg: []                         |                                                              |
| log.format_string                      | string | 日志字段配置                                                 | %(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s:%(lineno)d [-] %(message)s |
| log.date_format_string                 | string | 日志时间格式                                                 | %Y-%m-%d %H:%M:%S                                            |
| log.loggers                            | list   | 模块独立日志配置,列表每个元素是dict: [{"name": "cms.test.api", "path": "api.log"}] |                                                              |
| log.loggers.name                       | string | 模块名称路径,如cms.apps.test,可以被重复定义使用            |                                                              |
| log.loggers.level                      | string | 参考log.level                                                |                                                              |
| log.loggers.path                       | string | 参考log.path                                                 |                                                              |
| log.loggers.handler[^ 7]               | string | 参考log.handler                                              |                                                              |
| log.loggers.handler_args[^ 7]          | list   | 参考log.handler_args                                         |                                                              |
| log.loggers.propagate[^ 7]             | bool   | 是否传递到上一级日志配置                                     |                                                              |
| log.loggers.log_console[^ 7]           | bool   | 参考log.log_console                                          |                                                              |
| log.loggers.format_string[^ 7]         | string | 参考log.format_string                                        |                                                              |
| log.loggers.date_format_string[^ 7]    | string | 参考log.date_format_string                                   |                                                              |
| db                                     | dict   | 默认数据库配置项,用户可以自行定义其他DB配置项,但需要自己初始化DBPool对象(可以参考DefaultDBPool进行单例控制) |                                                              |
| db.connection                          | string | 连接字符串                                                   |                                                              |
| db.pool_size                           | int    | 连接池大小                                                   | 3                                                            |
| db.pool_recycle                        | int    | 连接最大空闲时间,超过时间后自动回收                         | 3600                                                         |
| db.pool_timeout                        | int    | 获取连接超时时间,单位秒                                     | 5                                                            |
| db.max_overflow                        | int    | 突发连接池扩展大小                                           | 5                                                            |
| dbs[^ 7]                               | dict   | 额外的数据库配置项,{name: {db conf...}},配置项会被初始化到pool.POOLS中,并以名称作为引用名,示例见进阶开发->多数据库支持 |                                                              |
| dbcrud                                 | dict   | 数据库CRUD控制项                                             |                                                              |
| dbcrud.unsupported_filter_as_empty     | bool   | 当遇到不支持的filter时的默认行为,1是返回空结果,2是忽略不支持的条件,由于历史版本的行为默认为2,因此其默认值为False,即忽略不支持的条件 | False                                                        |
| dbcrud.dynamic_relationship            | bool   | 是否启用ORM的动态relationship加载技术,启用后可以通过models.attributes来控制外键动态加载,避免数据过载导致查询缓慢 | True                                                         |
| dbcrud.dynamic_load_method             | string | 启用ORM的动态relationship加载技术后,可指定加载方式:joinedload,subqueryload,selectinload,immediateload<br/>**joinedload**:使用outer join将所有查询连接为一个语句,结果集少时速度最快,随着结果集和级联外键数量的增加,字段的展开会导致数据极大而加载缓慢<br/>**subqueryload**:比较折中的方式,使用外键独立sql查询,结果集少时速度较快,随着结果集和级联外键数量的增加,速度逐步优于joinedload<br/>**selectinload**:类似subqueryload,但每个查询使用结果集的主键组合为in查询,速度慢<br/>**immediateload**:类似SQLAlchemy的select懒加载,每行的外键单独使用一个查询,速度最慢<br/> | joinedload                                                   |
| dbcrud.detail_relationship_as_summary  | bool   | 控制获取详情时,下级relationship是列表级或摘要级,False为列表级,True为摘要级,默认False | False                                                        |
| cache                                  | dict   | 缓存配置项                                                   |                                                              |
| cache.type                             | string | 缓存后端类型                                                 | dogpile.cache.memory                                         |
| cache.expiration_time                  | int    | 缓存默认超时时间,单位为秒                                   | 3600                                                         |
| cache.arguments                        | dict   | 缓存额外配置                                                 | None                                                         |
| application                            | dict   |                                                              |                                                              |
| application.names                      | list   | 加载的应用列表,每个元素为string,代表加载的app路径          | []                                                           |
| rate_limit                             | dict   | 频率限制配置项                                               |                                                              |
| rate_limit.enabled                     | bool   | 是否启用频率限制                                             | False                                                        |
| rate_limit.storage_url                 | string | 频率限制数据存储计算后端                                     | memory://                                                    |
| rate_limit.strategy                    | string | 频率限制算法,可选fixed-window,fixed-window-elastic-expiry,moving-window | fixed-window                                                 |
| rate_limit.global_limits               | string | 全局频率限制(依赖于全局中间件),eg. 1/second; 5/minute       | None                                                         |
| rate_limit.per_method                  | bool   | 是否为每个HTTP方法独立频率限制                               | True                                                         |
| rate_limit.header_reset                | string | HTTP响应头,频率重置时间                                     | X-RateLimit-Reset                                            |
| rate_limit.header_remaining            | string | HTTP响应头,剩余的访问次数                                   | X-RateLimit-Remaining                                        |
| rate_limit.header_limit                | string | HTTP响应头,最大访问次数                                     | X-RateLimit-Limit                                            |
| celery                                 | dict   | 异步任务配置项                                               |                                                              |
| celery.talos_on_user_schedules_changed | list   | 定时任务变更判断函数列表"talos_on_user_schedules_changed":["cms.workers.hooks:ChangeDetection"], |                                                              |
| celery.talos_on_user_schedules         | list   | 定时任务函数列表"talos_on_user_schedules": ["cms.workers.hooks:AllSchedules"] |                                                              |
| worker                                 | dict   | 异步工作进程配置项                                           |                                                              |
| worker.callback                        | dict   | 异步工作进程回调控制配置项                                   |                                                              |
| worker.callback.strict_client          | bool   | 异步工作进程认证时仅使用直连IP                               | True                                                         |
| worker.callback.allow_hosts            | list   | 异步工作进程认证主机IP列表,当设置时,仅允许列表内worker调用回调 | None                                                         |
| worker.callback.name.%s.allow_hosts    | list   | 异步工作进程认证时,仅允许列表内worker调用此命名回调         | None                                                         |



## CHANGELOG

1.3.6:

- 更新:[crud] relationship的多属性 & 多级嵌套 查询支持
- 修复:[utils] http模块的i18n支持

1.3.5:

- 修复:[crud] _addtional_update的after_update参数取值无效问题

1.3.4:
- 修复:[crud] update & delete时带入default_orders报错问题

1.3.3:

- 更新:[config] 优化config.item效率
- 更新:[crud] 优化deepcopy导致的效率问题
- 更新:[utils] 优化utils.get_function_name效率
- 更新:[crud] 提供register_filter支持外部filter注册
- 修复:[crud] any_orm_data返回字段不正确问题

1.3.2:

- 更新:[i18n] 支持多语言包加载,并默认第一语言(language: [en, zh, zh-CN,...])
- 修复:[crud] update relationship后返回的对象不是最新信息问题

1.3.1:

- 更新:[db] models动态relationship加载,效率提升(CONF.dbcrud.dynamic_relationship,默认已启用),并可以指定load方式(默认joinedload)

- 更新:[db] 支持设定获取资源detail级时下级relationship指定列表级 / 摘要级(CONF.dbcrud.detail_relationship_as_summary)

- 更新:[test]动态relationship加载/装饰器/异常/缓存/导出/校验器/控制器模块等大量单元测试

- 更新**[breaking]**:[controller]_build_criteria的supported_filters由fnmatch更改为re匹配方式
  > 由fnmatch更改为re匹配,提升效率,也提高了匹配自由度
  >
  > 如果您的项目中使用了supported_filters=['name\_\_\*']类似的指定支持参数,需要同步更新代码如:['name\_\_.\*']
  >
  > 如果仅使用过supported_filters=['name']类的指定支持参数,则依然兼容无需更改

- 更新:[controller]_build_criteria支持unsupported_filter_as_empty配置(启用时,不支持参数将导致函数返回None)

- 更新:[controller]增加redirect重定向函数

- 修复:[controller]支持原生falcon的raise HTTPTemporaryRedirect(...)形式重定向

- 修复:[util] xmlutils的py2/py3兼容问题

- 修复:[schedule] TScheduler概率丢失一个max_interval时间段定时任务问题

- 修复:[middleware]falcon>=2.0 且使用wsgiref.simple_server时block问题

1.3.0:

- 新增:[db] 多数据库连接池配置支持(CONF.dbs)
- 新增:[worker] 远程调用快捷模式(callback.remote(...))
- 新增:[cache] 基于redis的分布式锁支持(cache.distributed_lock)
- 新增:[exception] 抛出异常可携带额外数据(raise Error(exception_data=...),  e.to_dict())
- 更新:[exception] 默认捕获所有异常,返回统一异常结构
- 更新:[exception] 替换异常序列化to_xml库,由dicttoxml库更换为talos.core.xmlutils,提升效率,支持更多扩展
- 更新:[template] 生成模板:requirements,wsgi_server,celery_worker
- 更新:[base] 支持falcon 2.0
- 更新:[log] 支持自定义handler的log配置
- 更新:[util] 支持协程级别的GLOABLS(支持thread/gevent/eventlet类型的worker)
- 修复:[base] 单元素的query数组错误解析为一个元素而非数组问题
- 修复:[util] exporter对异常编码的兼容问题
- 修复:[crud] create/update重复校验输入值

1.2.3:

- 优化:[config] 支持配置项变量/拦截/预渲染(常用于配置项的加解密) 

1.2.2:

- 优化:[util] 频率限制,支持类级/函数级频率限制,更多复杂场景 
- 优化:[test] 完善单元测试 
- 优化:[base] JSONB复杂查询支持 
- 优化:[base] 一些小细节

1.2.1:
- 见 [tags](https://gitee.com/wu.jianjun/talos/tags)

...



[^ 1]: 本文档基于v1.1.8版本,并增加了后续版本的一些特性描述
[^ 2]: v1.1.9版本中新增了TScheduler支持动态的定时任务以及更丰富的配置定义定时任务
[^ 3]: v1.1.8版本中仅支持这类简单的定时任务
[^ 4]: v1.2.0版本增加了__fields字段选择 以及 null, notnull, nlike, nilike的查询条件 以及 relationship查询支持
[^ 5]: v1.2.0版本新增\$or,\$and查询支持
[^ 6]: v1.2.3版本后开始支持
[^ 7]: v1.3.0版本新增多数据库连接池支持以及日志handler选项
[^ 8]: v1.3.0版本新增了Config项加载时的warnings,以提醒用户此配置项正确访问方式
[^ 9]: v1.3.1版本更新了relationship的动态加载技术,可根据设定的attributes自动加速查询(默认启用)

            

Raw data

            {
    "_id": null,
    "home_page": "https://gitee.com/wu.jianjun/talos",
    "name": "talos-api",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "talos automation restful rest api celery sqlalchemy falcon",
    "author": "Roy",
    "author_email": "wjjroy@outlook.com",
    "download_url": "https://files.pythonhosted.org/packages/bf/26/88c8908169c43d6885544f9579fee02fc35670a093f5ab55a0ea3e5ee397/talos-api-1.3.7.tar.gz",
    "platform": null,
    "description": "talos project[^ 1]\n[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n![](https://img.shields.io/badge/language-python-orang.svg)\n![](https://img.shields.io/pypi/dm/talos-api?style=flat)\n\n=======================\n\n[TOC]\n\n\n\n## \u7279\u6027\n\nhttps://gitee.com/wu.jianjun/talos/tree/master/release\n\n\u9879\u76ee\u662f\u4e3b\u8981\u57fa\u4e8efalcon\u548cSQLAlchemy\u5c01\u88c5\uff0c\u63d0\u4f9b\u5e38\u7528\u7684\u9879\u76ee\u5de5\u5177\uff0c\u4fbf\u4e8e\u7528\u6237\u7f16\u5199API\u670d\u52a1\n\u9879\u76ee\u63d0\u4f9b\u4e86\u5de5\u5177talos_generator\uff0c\u53ef\u4ee5\u81ea\u52a8\u4e3a\u60a8\u751f\u6210\u57fa\u4e8etalos\u7684api\u5e94\u7528\uff0c\u5e76\u4e14\u76ee\u5f55\u7ed3\u6784\u57fa\u4e8epython\u6807\u51c6\u5305\u7ba1\u7406\n\n* \u57fa\u4e8efalcon\uff0c\u9ad8\u6548\n* \u4f7f\u7528SQLAlchemy\u4f5c\u4e3a\u6570\u636e\u5e93\u540e\u7aef\uff0c\u5feb\u901f\u5207\u6362\u6570\u636e\u5e93\n* \u9879\u76ee\u751f\u6210\u5de5\u5177\n* \u5feb\u901fRESTful CRUD API\u5f00\u53d1\n* filters\uff0cpagination\uff0corders\u652f\u6301\n* validation\u6570\u636e\u6821\u9a8c\n* \u5f02\u6b65\u4efb\u52a1\u96c6\u6210[celery]\n* \u5b9a\u65f6\u4efb\u52a1\u96c6\u6210[celery]\n* \u9891\u7387\u9650\u5236\n* \u56fd\u9645\u5316i18n\u652f\u6301\n* SMTP\u90ae\u4ef6\u3001AD\u57df\u3001CSV\u5bfc\u51fa\u3001\u7f13\u5b58\u7b49\u5e38\u7528\u6a21\u5757\u96c6\u6210\n\n\u9996\u5148\u5b89\u88c5talos,\u8fd0\u884ctalos\u751f\u6210\u5de5\u5177\u751f\u6210\u9879\u76ee\n\n\u63a8\u8350\u901a\u8fc7pip\u5b89\u88c5\n\n```bash\npip install talos-api\n```\n\n\u6216\u8005\u901a\u8fc7\u6e90\u7801\u5b89\u88c5\n\n```bash\npython setup.py install\n```\n\n\n\n## \u9879\u76ee\u751f\u6210\n\n\u5b89\u88c5talos\u540e\uff0c\u4f1a\u751f\u6210talos_generator\u5de5\u5177\uff0c\u6b64\u5de5\u5177\u53ef\u4ee5\u4e3a\u7528\u6237\u5feb\u901f\u751f\u6210\u4e1a\u52a1\u4ee3\u7801\u6846\u67b6\n\n```bash\n> talos_generator\n> \u8bf7\u8f93\u5165\u9879\u76ee\u751f\u6210\u76ee\u5f55\uff1a./\n> \u8bf7\u8f93\u5165\u9879\u76ee\u540d\u79f0(\u82f1)\uff1acms\n> \u8bf7\u8f93\u5165\u751f\u6210\u7c7b\u578b[project,app,\u5176\u4ed6\u5185\u5bb9\u9000\u51fa]\uff1aproject\n> \u8bf7\u8f93\u5165\u9879\u76ee\u7248\u672c\uff1a1.2.4\n> \u8bf7\u8f93\u5165\u9879\u76ee\u4f5c\u8005\uff1aRoy\n> \u8bf7\u8f93\u5165\u9879\u76ee\u4f5c\u8005Email\uff1aroy@test.com\n> \u8bf7\u8f93\u5165\u9879\u76ee\u542f\u52a8\u914d\u7f6e\u76ee\u5f55\uff1a./etc #\u6b64\u5904\u586b\u5199\u9ed8\u8ba4\u914d\u7f6e\u8def\u5f84\uff0c\u76f8\u5bf9\u8def\u5f84\u662f\u76f8\u5bf9\u9879\u76ee\u6587\u4ef6\u5939\uff0c\u4e5f\u53ef\u4ee5\u662f\u7edd\u5bf9\u8def\u5f84\n> \u8bf7\u8f93\u5165\u9879\u76eeDB\u8fde\u63a5\u4e32\uff1apostgresql+psycopg2://postgres:123456@127.0.0.1/testdb [SQLAlchemy\u7684DB\u8fde\u63a5\u4e32]\n### \u521b\u5efa\u9879\u76ee\u76ee\u5f55\uff1a./cms\n### \u521b\u5efa\u9879\u76ee\uff1acms(1.2.4)\u901a\u7528\u6587\u4ef6\n### \u521b\u5efa\u542f\u52a8\u670d\u52a1\u811a\u672c\n### \u521b\u5efa\u542f\u52a8\u914d\u7f6e\uff1a./etc/cms.conf\n### \u521b\u5efa\u4e2d\u95f4\u4ef6\u76ee\u5f55\n### \u5b8c\u6210\n> \u8bf7\u8f93\u5165\u751f\u6210\u7c7b\u578b[project,app,\u5176\u4ed6\u5185\u5bb9\u9000\u51fa]\uff1aapp # \u751f\u6210\u7684APP\u7528\u4e8e\u7f16\u5199\u5b9e\u9645\u4e1a\u52a1\u4ee3\u7801\uff0c\u6216\u624b\u52a8\u7f16\u5199\n### \u8bf7\u8f93\u5165app\u540d\u79f0(\u82f1)\uff1auser\n### \u521b\u5efaapp\u76ee\u5f55\uff1a./cms/cms/apps\n### \u521b\u5efaapp\u811a\u672c\uff1auser\n### \u5b8c\u6210\n> \u8bf7\u8f93\u5165\u751f\u6210\u7c7b\u578b[project,app,\u5176\u4ed6\u5185\u5bb9\u9000\u51fa]\uff1a\n```\n\n\u9879\u76ee\u751f\u6210\u540e\uff0c\u4fee\u6539\u914d\u7f6e\u6587\u4ef6\uff0c\u6bd4\u5982**./etc/cms.conf\u7684application.names\u914d\u7f6e\uff0c\u5217\u8868\u4e2d\u52a0\u5165\"cms.apps.user\"\u5373\u53ef\u542f\u52a8\u670d\u52a1\u5668\u8fdb\u884c\u8c03\u8bd5**\n\n\n\n\n## \u5f00\u53d1\u8c03\u8bd5\n\u542f\u52a8\u9879\u76ee\u76ee\u5f55\u4e0b\u7684server/simple_server.py\u5373\u53ef\u8fdb\u884c\u8c03\u8bd5\n\n\n\n## \u751f\u4ea7\u90e8\u7f72\n  - \u6e90\u7801\u6253\u5305\n\n```bash\npip install wheel\npython setup.py bdist_wheel\npip install cms-1.2.4-py2.py3-none-any.whl\n```\n\n  - \u542f\u52a8\u670d\u52a1\uff1a\n\n```bash\n# Linux\u90e8\u7f72\u4e00\u822c\u914d\u7f6e\u6587\u4ef6\u90fd\u4f1a\u653e\u5728/etc/cms/\u4e0b\uff0c\u5305\u62eccms.conf\u548cgunicorn.py\u6587\u4ef6\n# \u5e76\u786e\u4fdd\u5b89\u88c5gunicorn\npip install gunicorn\n# \u6b65\u9aa4\u4e00\uff0c\u5bfc\u51fa\u73af\u5883\u53d8\u91cf\uff1a\nexport CMS_CONF=/etc/cms/cms.conf\n# \u6b65\u9aa4\u4e8c\uff0c\ngunicorn --pid \"/var/run/cms.pid\" --config \"/etc/cms/gunicorn.py\" \"cms.server.wsgi_server:application\"\n```\n\n\n\n## API\u5f00\u53d1\u5f15\u5bfc\n\n### \u57fa\u7840\u5f00\u53d1\u6b65\u9aa4\n\n#### \u8bbe\u8ba1\u6570\u636e\u5e93\n\n\u7565(talos\u8981\u6c42\u81f3\u5c11\u6709\u4e00\u5217\u552f\u4e00\u6027\uff0c\u5426\u5219\u65e0\u6cd5\u63d0\u4f9bitem\u578b\u64cd\u4f5c)\n\n#### \u5bfc\u51fa\u6570\u636e\u5e93\u6a21\u578b\n\ntalos\u4e2d\u4f7f\u7528\u7684\u662fSQLAlchemy\uff0c\u4f7f\u7528\u8868\u64cd\u4f5c\u9700\u8981\u5c06\u6570\u636e\u5e93\u5bfc\u51fa\u4e3apython\u5bf9\u8c61\u5b9a\u4e49\uff0c\u8fd9\u6837\u505a\u7684\u597d\u5904\u662f\n\n1. \u786e\u5b9a\u8868\u7ed3\u6784\uff0c\u5f62\u6210\u5e94\u7528\u4ee3\u7801\u4e0e\u6570\u636e\u5e93\u4e4b\u95f4\u7684\u7248\u672c\u5bf9\u5e94\n2. \u4fbf\u4e8e\u7f16\u7a0b\u4e2d\u8868\u8fbe\u6570\u636e\u5e93\u64cd\u4f5c\uff0c\u800c\u5e76\u975e\u4f7f\u7528\u5b57\u7b26\u4e32\n3. SQLAlchemy\u7684\u591a\u6570\u636e\u5e93\u652f\u6301\uff0c\u5f3a\u5927\u7684\u8868\u8fbe\u80fd\u529b\n\n```bash\npip install sqlacodegen\nsqlacodegen postgresql+psycopg2://postgres:123456@127.0.0.1/testdb --outfile models.py\n```\n\n\u751f\u6210\u7684models.py\u5185\u5bb9\u5927\u81f4\u5982\u4e0b\uff1a\n\n```python\n# coding=utf-8\n\nfrom __future__ import absolute_import\n\nfrom sqlalchemy import String\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\nmetadata = Base.metadata\n\nclass User(Base):\n    __tablename__ = 'user'\n\n    id = Column(String(36), primary_key=True)\n    name = Column(String(63), nullable=False)\n```\n\n\u5f53\u7136\u8fd9\u4e2a\u5bfc\u51fa\u64cd\u4f5c\u5982\u679c\u5728\u8db3\u591f\u719f\u6089\u7684\u60c5\u51b5\u4e0b\u53ef\u4ee5\u624b\u52a8\u7f16\u5199\uff0c\u4e0d\u9700\u8981\u5bfc\u51fa\u5de5\u5177\n\n#### \u6570\u636e\u5e93\u6a21\u578b\u7c7b\u7684\u9b54\u6cd5\u7c7b\n\n\u5c06\u5bfc\u51fa\u7684\u6587\u4ef6\u8868\u5185\u5bb9\u590d\u5236\u5230cms.db.models.py\u4e2d\uff0c\u5e76\u4e3a\u6bcf\u4e2a\u8868\u8bbe\u7f6eDictBase\u57fa\u7c7b\u7ee7\u627f\n\nmodels.py\u6587\u4ef6\u4e2d\uff0c\u6bcf\u4e2a\u8868\u5bf9\u5e94\u7740\u4e00\u4e2aclass\uff0c\u8fd9\u4f7f\u5f97\u6211\u4eec\u5728\u5f00\u53d1\u4e1a\u52a1\u5904\u7406\u4ee3\u7801\u65f6\u80fd\u660e\u786e\u8868\u5bf9\u5e94\u7684\u5904\u7406\uff0c\u4f46\u5728\u63a5\u53e3\u8fd4\u56de\u4e2d\uff0c\u6211\u4eec\u901a\u5e38\u9700\u8981\u8f6c\u6362\u4e3ajson\uff0c\u56e0\u800c\uff0c\u6211\u4eec\u9700\u8981\u4e3amodels.py\u4e2d\u7684\u6bcf\u4e2a\u8868\u7684\u7c7b\u589e\u52a0\u4e00\u4e2a\u7ee7\u627f\u5173\u7cfb\uff0c\u4ee5\u4fbf\u4e3a\u5b83\u63d0\u4f9b\u8f6c\u6362\u7684\u652f\u6301\n\n\u5904\u7406\u5b8c\u540e\u7684models.py\u6587\u4ef6\u5982\u4e0b\uff1a\n\n```python\n# coding=utf-8\n\nfrom __future__ import absolute_import\n\nfrom sqlalchemy import String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom talos.db.dictbase import DictBase\n\nBase = declarative_base()\nmetadata = Base.metadata\n\nclass User(Base, DictBase):\n    __tablename__ = 'user'\n\n    id = Column(String(36), primary_key=True)\n    name = Column(String(63), nullable=False)\n\nclass UserPhoneNum(Base, DictBase):\n    __tablename__ = 'user_phone'\n\n    user_id = Column(String(63), nullable=False, primary_key=True)\n    phone = Column(String(63), nullable=False, primary_key=True)\n    description = Column(String(255), nullable=True)\n```\n\n\u7ee7\u627f\u4e86\u8fd9\u4e2a\u7c7b\u4e4b\u540e\uff0c\u4e0d\u4ec5\u63d0\u4f9b\u4e86\u8f6c\u6362\u63a5\u53e3json\u7684\u80fd\u529b\uff0c\u8fd8\u63d0\u4f9b\u4e86\u5b57\u6bb5\u63d0\u53d6\u7684\u80fd\u529b\uff0c\u6b64\u5904\u6ca1\u6709\u6307\u5b9a\u5b57\u6bb5\u63d0\u53d6\uff0c\u5219\u610f\u5473\u7740\u9ed8\u8ba4\u4f7f\u7528\u8868\u7684\u6240\u6709\u5b57\u6bb5\uff08list\u548c\u88ab\u5176\u4ed6\u8868\u5916\u952e\u5f15\u7528\u65f6\u9ed8\u8ba4\u4e0d\u5305\u542b\u5916\u952e\u5b57\u6bb5\uff09\uff0c\u5982\u679c\u9700\u8981\u81ea\u5b9a\u4e49\u5b57\u6bb5\uff0c\u53ef\u4ee5\u5728\u7c7b\u4e2d\u914d\u7f6e\u5b57\u6bb5\u63d0\u53d6\uff1a\n\n```python\nclass User(Base, DictBase):\n    __tablename__ = 'user'\n    # \u7528\u4e8e\u63a7\u5236\u83b7\u53d6\u5217\u8868\u65f6\u5b57\u6bb5\u8fd4\u56de\n    attributes = ['id', 'name']\n    # \u7528\u4e8e\u63a7\u5236\u83b7\u53d6\u8be6\u60c5\u65f6\u5b57\u6bb5\u8fd4\u56de\n    detail_attributes = attributes\n    # \u7528\u4e8e\u63a7\u5236\u88ab\u5176\u4ed6\u8d44\u6e90\u5916\u952e\u5f15\u7528\u65f6\u5b57\u6bb5\u8fd4\u56de\n    summary_attributes = ['name']\n    \n    id = Column(String(36), primary_key=True)\n    name = Column(String(63), nullable=False)\n```\n**\u6307\u5b9aattributes/detail_attributes/summary_attributes\u662f\u975e\u5e38\u6709\u6548\u7684\u5b57\u6bb5\u8fd4\u56de\u63a7\u5236\u624b\u6bb5\uff0c\u51cf\u5c11\u8fd4\u56de\u7684\u4fe1\u606f\uff0c\u53ef\u4ee5\u51cf\u5c11\u670d\u52a1\u5668\u4f20\u8f93\u7684\u538b\u529b\uff0c\u4e0d\u4ec5\u5982\u6b64\uff0c\u5982\u679c\u6b64\u5904\u6709\u5916\u952erelationship\u65f6\uff0c\u6307\u5b9a\u5404attributes\u5c5e\u6027\u8fd8\u53ef\u4ee5\u6709\u6548\u7684\u63a7\u5236\u6570\u636e\u5e93\u5bf9\u4e8e\u5916\u952e\u7684\u67e5\u8be2\u6548\u7387** [^ 9]\n\n> \u6269\u5c55\u9605\u8bfb\uff1a\n>\n> \u4e00\u4e2a\u8f83\u4e3a\u5e38\u89c1\u7684\u573a\u666f\uff0c\u67d0\u7cfb\u7edf\u8bbe\u8ba1\u6709\u6570\u636e\u5e93\u8868\u5982\u4e0b\uff1a\n> User -> PhoneNum/Addresses, \u4e00\u4e2a\u7528\u6237\u5bf9\u5e94\u591a\u4e2a\u7535\u8bdd\u53f7\u7801\u4ee5\u53ca\u591a\u4e2a\u5730\u5740\n> Tag\uff0c\u6807\u7b7e\u8868\uff0c\u4e00\u4e2a\u8d44\u6e90\u53ef\u5bf9\u5e94\u591a\u4e2a\u6807\u7b7e\n> Region -> Tag\uff0c\u5730\u57df\u8868\uff0c\u4e00\u4e2a\u5730\u57df\u6709\u591a\u4e2a\u6807\u7b7e\n> Resource -> Region/Tag\uff0c\u8d44\u6e90\u8868\uff0c\u4e00\u4e2a\u8d44\u6e90\u5c5e\u4e8e\u4e00\u4e2a\u5730\u57df\uff0c\u4e00\u4e2a\u8d44\u6e90\u6709\u591a\u4e2a\u6807\u7b7e\n>\n> \u7528models\u8868\u793a\u5927\u81f4\u5982\u4e0b\uff1a\n>\n> ```python\n> class Address(Base, DictBase):\n>     __tablename__ = 'address'\n>     attributes = ['id', 'location', 'user_id']\n>     detail_attributes = attributes\n>     summary_attributes = ['location']\n> \n>     id = Column(String(36), primary_key=True)\n>     location = Column(String(255), nullable=False)\n>     user_id = Column(ForeignKey(u'user.id'), nullable=False)\n> \n>     user = relationship(u'User')\n>     \n> class PhoneNum(Base, DictBase):\n>     __tablename__ = 'phone'\n>     attributes = ['id', 'number', 'user_id']\n>     detail_attributes = attributes\n>     summary_attributes = ['number']\n> \n>     id = Column(String(36), primary_key=True)\n>     number = Column(String(255), nullable=False)\n>     user_id = Column(ForeignKey(u'user.id'), nullable=False)\n> \n>     user = relationship(u'User')\n>     \n> class User(Base, DictBase):\n>     __tablename__ = 'user'\n>     attributes = ['id', 'name', 'addresses', 'phonenums']\n>     detail_attributes = attributes\n>     summary_attributes = ['name']\n> \n>     id = Column(String(36), primary_key=True)\n>     name = Column(String(255), nullable=False)\n>     \n>     addresses = relationship(u'Address', back_populates=u'user', lazy=False, uselist=True, viewonly=True)\n>     phonenums = relationship(u'PhoneNum', back_populates=u'user', lazy=False, uselist=True, viewonly=True)\n>     \n> class Tag(Base, DictBase):\n>     __tablename__ = 'tag'\n>     attributes = ['id', 'res_id', 'key', 'value']\n>     detail_attributes = attributes\n>     summary_attributes = ['key', 'value']\n> \n>     id = Column(String(36), primary_key=True)\n>     res_id = Column(String(36), nullable=False)\n>     key = Column(String(36), nullable=False)\n>     value = Column(String(36), nullable=False)\n> \n> class Region(Base, DictBase):\n>     __tablename__ = 'region'\n>     attributes = ['id', 'name', 'desc', 'tags', 'user_id', 'user']\n>     detail_attributes = attributes\n>     summary_attributes = ['name', 'desc']\n> \n>     id = Column(String(36), primary_key=True)\n>     name = Column(String(255), nullable=False)\n>     desc = Column(String(255), nullable=True)\n>     user_id = Column(ForeignKey(u'user.id'), nullable=True)\n>     user = relationship(u'User')\n> \n>     tags = relationship(u'Tag', primaryjoin='foreign(Region.id) == Tag.res_id',\n>         lazy=False, viewonly=True, uselist=True)\n> \n> class Resource(Base, DictBase):\n>     __tablename__ = 'resource'\n>     attributes = ['id', 'name', 'desc', 'tags', 'user_id', 'user', 'region_id', 'region']\n>     detail_attributes = attributes\n>     summary_attributes = ['name', 'desc']\n> \n>     id = Column(String(36), primary_key=True)\n>     name = Column(String(255), nullable=False)\n>     desc = Column(String(255), nullable=True)\n>     user_id = Column(ForeignKey(u'user.id'), nullable=True)\n>     region_id = Column(ForeignKey(u'region.id'), nullable=True)\n>     user = relationship(u'User')\n>     region = relationship(u'region')\n> \n>     tags = relationship(u'Tag', primaryjoin='foreign(Resource.id) == Tag.res_id',\n>         lazy=False, viewonly=True, uselist=True)\n> ```\n>\n> \u5982\u4e0a\uff0cuser\u4f5c\u4e3a\u6700\u5e95\u5c42\u7684\u8d44\u6e90\uff0c\u88abregion\u5f15\u7528\uff0c\u800cregion\u53c8\u88abresource\u4f7f\u7528\uff0c\u5bfc\u81f4\u5c42\u7ea7\u5d4c\u5957\u6781\u591a\uff0c\u5728SQLAlchmey\u4e2d\uff0c\u5982\u679c\u5e0c\u671b\u5feb\u901f\u67e5\u8be2\u4e00\u4e2a\u5217\u8868\u8d44\u6e90\uff0c\u4e00\u822c\u800c\u8a00\u6211\u4eec\u4f1a\u5728relationship\u4e2d\u52a0\u4e0alazy=False\uff0c\u8fd9\u6837\u5c31\u53ef\u4ee5\u8ba9\u4fe1\u606f\u5728\u4e00\u6b21sql\u67e5\u8be2\u4e2d\u52a0\u8f7d\u51fa\u6765\uff0c\u800c\u4e0d\u662f\u6bcf\u6b21\u8bbf\u95ee\u5916\u952e\u5c5e\u6027\u518d\u53d1\u8d77\u4e00\u6b21\u67e5\u8be2\u3002\u95ee\u9898\u5728\u4e8e\uff0clazy=False\u65f6sql\u88ab\u7ec4\u5408\u4e3a\u4e00\u4e2aSQL\u8bed\u53e5\uff0crelationship\u6bcf\u7ea7\u5d4c\u5957\u4f1a\u88ab\u5c55\u5f00\uff0c\u5b9e\u9645\u6570\u636e\u5e93\u67e5\u8be2\u7ed3\u679c\u5c06\u662f\u4e58\u6570\u7ea7\uff1anum_resource\\*num_resource_user\\*num_resource_user_address\\*num_resource_user_phonenum\\*num_region\\*num_region_user_address\\*num_region_user_phonenum...\n>\n> \u8f83\u5dee\u7684\u60c5\u51b5\u4e0b\u53ef\u80fd\u56de\u5bfc\u81f4resource\u8868\u53ea\u67091k\u6570\u91cf\u7ea7\uff0c\u800c\u672c\u6b21\u67e5\u8be2\u7ed3\u679c\u5374\u662f1000 \\* 1k\u7ea7\n> \u901a\u5e38\u6211\u4eec\u52a0\u8f7dresource\u65f6\uff0c\u6211\u4eec\u5e76\u4e0d\u9700\u8981region.user\u3001region.tags\u3001user.addresses\u3001user.phonenums\u7b49\u4fe1\u606f\uff0c\u901a\u8fc7\u6307\u5b9asummary_attributes\u6765\u9632\u6b62\u6570\u636e\u8fc7\u8f7d\uff08\u9700\u8981\u542f\u7528CONF.dbcrud.dynamic_relationship\uff0c\u9ed8\u8ba4\u542f\u7528\uff09\uff0c\u8fd9\u6837\u6211\u4eec\u5f97\u5230\u7684SQL\u67e5\u8be2\u662f\u975e\u5e38\u5feb\u901f\u7684\uff0c\u7ed3\u679c\u96c6\u4e5f\u4fdd\u6301\u548cresource\u4e00\u4e2a\u6570\u91cf\u7ea7\n\n\n\n#### \u589e\u5220\u6539\u67e5\u7684\u8d44\u6e90\u7c7b\n\n\u5728cms.db\u4e2d\u65b0\u589eresource.py\u6587\u4ef6\uff0c\u5185\u5bb9\u5982\u4e0b\uff1a\n\n```python\n# coding=utf-8\n\nfrom __future__ import absolute_import\n\nfrom talos.db.crud import ResourceBase\n\nfrom cms.db import models\n\n\nclass User(ResourceBase):\n    orm_meta = models.User\n    _primary_keys = 'id'\n\n\nclass UserPhoneNum(ResourceBase):\n    orm_meta = models.UserPhoneNum\n    _primary_keys = ('user_id', 'phone')\n```\n\n\u5b8c\u6210\u6b64\u9879\u5b9a\u4e49\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528resource.User\u6765\u8fdb\u884c\u7528\u6237\u8868\u7684\u589e\u5220\u6539\u67e5\uff0c\u800c\u8fd9\u4e9b\u529f\u80fd\u90fd\u662fResourceBase\u9ed8\u8ba4\u63d0\u4f9b\u7684\u80fd\u529b\n\u53ef\u4ee5\u770b\u5230\u6211\u4eec\u6b64\u5904\u5b9a\u4e49\u4e86orm_meta\u548c_primary_keys\u4e24\u4e2a\u7c7b\u5c5e\u6027\uff0c\u9664\u6b64\u4ee5\u5916\u8fd8\u6709\u66f4\u591a\u7c7b\u5c5e\u6027\u53ef\u4ee5\u5e2e\u52a9\u6211\u4eec\u5feb\u901f\u914d\u7f6e\u5e94\u7528\u903b\u8f91\n\n| \u7c7b\u5c5e\u6027                          | \u9ed8\u8ba4\u503c | \u63cf\u8ff0                                                         |\n| ------------------------------- | ------ | ------------------------------------------------------------ |\n| orm_meta                        | None   | \u8d44\u6e90\u64cd\u4f5c\u7684SQLAlchmey Model\u7c7b[\u8868]                             |\n| orm_pool                        | None   | \u6307\u5b9a\u8d44\u6e90\u4f7f\u7528\u7684\u6570\u636e\u5e93\u8fde\u63a5\u6c60\uff0c\u9ed8\u8ba4\u4f7f\u7528defaultPool\uff0c\u5b9e\u4f8b\u521d\u59cb\u5316\u53c2\u6570\u4f18\u5148\u4e8e\u672c\u53c2\u6570 |\n| _dynamic_relationship           | None   | \u662f\u5426\u6839\u636eModel\u4e2d\u5b9a\u4e49\u7684attribute\u81ea\u52a8\u6539\u53d8load\u7b56\u7565\uff0c\u4e0d\u6307\u5b9a\u5219\u4f7f\u7528\u914d\u7f6e\u6587\u4ef6\u9ed8\u8ba4(True) |\n| _dynamic_load_method            | None   | \u542f\u7528\u52a8\u6001\u5916\u952e\u52a0\u8f7d\u7b56\u7565\u65f6\uff0c\u52a8\u6001\u52a0\u8f7d\u5916\u952e\u7684\u65b9\u5f0f\uff0c\u9ed8\u8ba4None\uff0c\u5373\u4f7f\u7528\u5168\u5c40\u914d\u7f6e\uff08\u5168\u5c40\u914d\u7f6e\u9ed8\u8ba4joinedload\uff09 <br/> joinedload \u7b80\u4fbf\uff0c\u5728\u5e38\u7528\u5c0f\u578b\u67e5\u8be2\u4e2d\u54cd\u5e94\u4f18\u4e8esubqueryload  <br/>subqueryload \u5728\u5927\u578b\u590d\u6742(\u591a\u5c42\u5916\u952e)\u67e5\u8be2\u4e2d\u54cd\u5e94\u4f18\u4e8ejoinedload |\n| _detail_relationship_as_summary | None   | \u8d44\u6e90get\u83b7\u53d6\u5230\u7684\u7b2c\u4e00\u5c42\u7ea7\u5916\u952e\u5b57\u6bb5\u7ea7\u522b\u662fsummary\u7ea7\uff0c\u5219\u8bbe\u7f6e\u4e3aTrue\uff0c\u5426\u5219\u4f7f\u7528\u914d\u7f6e\u6587\u4ef6\u9ed8\u8ba4(False) |\n| _primary_keys                   | 'id'   | \u8868\u5bf9\u5e94\u7684\u4e3b\u952e\u5217\uff0c\u5355\u4e2a\u4e3b\u952e\u65f6\uff0c\u4f7f\u7528\u5b57\u7b26\u4e32\uff0c\u591a\u4e2a\u8054\u5408\u4e3b\u952e\u65f6\u4e3a\u5b57\u7b26\u4e32\u5217\u8868\uff0c\u8fd9\u4e2a\u662f\u4e1a\u52a1\u4e3b\u952e\uff0c\u610f\u5473\u7740\u4f60\u53ef\u4ee5\u5b9a\u4e49\u548c\u6570\u636e\u5e93\u4e3b\u952e\u4e0d\u4e00\u6837\u7684\u5b57\u6bb5\uff08\u524d\u63d0\u662f\u8981\u786e\u5b9a\u8fd9\u4e9b\u5b57\u6bb5\u662f\u6709\u552f\u4e00\u6027\u7684\uff09 |\n| _default_filter                 | {}     | \u9ed8\u8ba4\u8fc7\u6ee4\u67e5\u8be2\uff0c\u5e38\u7528\u4e8e\u8f6f\u5220\u9664\uff0c\u6bd4\u5982\u6570\u636e\u5220\u9664\u6211\u4eec\u5728\u6570\u636e\u5e93\u5b57\u6bb5\u4e2d\u6807\u8bb0\u4e3ais_deleted=True\uff0c\u90a3\u4e48\u6211\u4eec\u518d\u6b21list\uff0cget\uff0cupdate\uff0cdelete\u7684\u65f6\u5019\u9700\u8981\u9ed8\u8ba4\u8fc7\u6ee4\u8fd9\u4e9b\u6570\u636e\u7684\uff0c\u7b49\u4ef7\u4e8e\u9ed8\u8ba4\u5e26\u6709where is_delete = True |\n| _default_order                  | []     | \u9ed8\u8ba4\u6392\u5e8f\uff0c\u67e5\u8be2\u8d44\u6e90\u65f6\u88ab\u5e94\u7528\uff0c('name', '+id', '-status'), +\u8868\u793a\u9012\u589e\uff0c-\u8868\u793a\u9012\u51cf\uff0c\u9ed8\u8ba4\u9012\u589e |\n| _validate                       | []     | \u6570\u636e\u8f93\u5165\u6821\u9a8c\u89c4\u5219\uff0c\u4e3atalos.db.crud.ColumnValidator\u5bf9\u8c61\u5217\u8868    |\n\n\u4e00\u4e2avalidate\u793a\u4f8b\u5982\u4e0b\uff1a\n\n```python\n   ColumnValidator(field='id',\n                   validate_on=['create:M']),\n   ColumnValidator(field='name',\n                   rule='1, 63',\n                   rule_type='length',\n                   validate_on=['create:M', 'update:O']),\n   ColumnValidator(field='enabled',\n                   rule=validator.InValidator(['true', 'false', 'True', 'False'])\n                   converter=converter.BooleanConverter(),\n                   validate_on=['create:M', 'update:O']),\n```\n\nColumnValidator\u53ef\u4ee5\u5b9a\u4e49\u7684\u5c5e\u6027\u5982\u4e0b\uff1a\n\n| \u5c5e\u6027         | \u7c7b\u578b                                           | \u63cf\u8ff0                                                         |\n| ------------ | ---------------------------------------------- | ------------------------------------------------------------ |\n| field        | \u5b57\u7b26\u4e32                                         | \u5b57\u6bb5\u540d\u79f0                                                     |\n| rule         | validator\u5bf9\u8c61 \u6216 \u6821\u9a8c\u7c7b\u578brule_type\u6240\u9700\u8981\u7684\u53c2\u6570 | \u5f53rule\u662fvalidator\u7c7b\u578b\u5bf9\u8c61\u65f6\uff0c\u5ffd\u7565 rule_type\u53c2\u6570              |\n| rule_type    | \u5b57\u7b26\u4e32                                         | \u7528\u4e8e\u5feb\u901f\u5b9a\u4e49\u6821\u9a8c\u89c4\u5219\uff0c\u9ed8\u8ba4regex\uff0c\u53ef\u9009\u7c7b\u578b\u6709callback\uff0cregex\uff0cemail\uff0cphone\uff0curl\uff0clength\uff0cin\uff0cnotin\uff0cinteger\uff0cfloat\uff0ctype |\n| validate_on  | \u6570\u7ec4                                           | \u6821\u9a8c\u573a\u666f\u548c\u5fc5\u8981\u6027, eg. ['create: M', 'update:O']\uff0c\u8868\u793a\u6b64\u5b57\u6bb5\u5728create\u51fd\u6570\u4e2d\u4e3a\u5fc5\u8981\u5b57\u6bb5\uff0cupdate\u51fd\u6570\u4e2d\u4e3a\u53ef\u9009\u5b57\u6bb5\uff0c\u4e5f\u53ef\u4ee5\u8868\u793a\u4e3a['*:M']\uff0c\u8868\u793a\u4efb\u4f55\u60c5\u51b5\u4e0b\u90fd\u662f\u5fc5\u8981\u5b57\u6bb5(**\u9ed8\u8ba4**) |\n| error_msg    | \u5b57\u7b26\u4e32                                         | \u9519\u8bef\u63d0\u793a\u4fe1\u606f\uff0c\u9ed8\u8ba4\u4e3a'%(result)s'\uff0c\u5373validator\u8fd4\u56de\u7684\u62a5\u9519\u4fe1\u606f\uff0c\u7528\u6237\u53ef\u4ee5\u56fa\u5b9a\u5b57\u7b26\u4e32\u6216\u4f7f\u7528\u5e26\u6709%(result)s\u7684\u6a21\u677f\u5b57\u7b26\u4e32 |\n| converter    | converter\u5bf9\u8c61                                  | \u6570\u636e\u8f6c\u6362\u5668\uff0c\u5f53\u6570\u636e\u88ab\u6821\u9a8c\u540e\uff0c\u53ef\u80fd\u9700\u8981\u8f6c\u6362\u4e3a\u56fa\u5b9a\u7c7b\u578b\u540e\u624d\u80fd\u8fdb\u884c\u7f16\u7a0b\u5904\u7406\uff0c\u8f6c\u6362\u5668\u53ef\u4ee5\u4e3a\u6b64\u63d0\u4f9b\u81ea\u52a8\u8f6c\u6362\uff0c\u6bd4\u5982\u7528\u6237\u8f93\u5165\u4e3a'2018-01-01 01:01:01'\u5b57\u7b26\u4e32\u65f6\u95f4\uff0c\u7a0b\u5e8f\u9700\u8981\u4e3aDatetime\u7c7b\u578b\uff0c\u5219\u53ef\u4ee5\u4f7f\u7528DateTimeConverter\u8fdb\u884c\u8f6c\u6362 |\n| orm_required | \u5e03\u5c14\u503c                                         | \u63a7\u5236\u6b64\u5b57\u6bb5\u662f\u5426\u4f1a\u88ab\u4f20\u9012\u5230\u6570\u636e\u5e93SQL\u4e2d\u53bb                        |\n| aliases      | \u6570\u7ec4                                           | \u5b57\u6bb5\u7684\u522b\u540d\uff0c\u6bd4\u5982\u63a5\u53e3\u5347\u7ea7\u540e\u4e3a\u4fdd\u7559\u524d\u5411\u517c\u5bb9\uff0c\u8001\u5b57\u6bb5\u53ef\u4ee5\u4f5c\u4e3a\u522b\u540d\u6307\u5411\u5230\u65b0\u540d\u79f0\u4e0a |\n| nullable     | \u5e03\u5c14\u503c                                         | \u63a7\u5236\u6b64\u5b57\u6bb5\u662f\u5426\u53ef\u4ee5\u4e3aNone\uff0c**\u9ed8\u8ba4False**                      |\n\nCRUD\u4f7f\u7528\u65b9\u5f0f:\n\n```python\nresource.User().create({'id': '1', 'name': 'test'})\nresource.User().list()\nresource.User().list({'name': 'test'})\nresource.User().list({'name': {'ilike': 'na'}}, offset=0, limit=5)\nresource.User().count()\nresource.User().count({'name': 'test'})\nresource.User().count({'name': {'ilike': 'na'}})\nresource.User().get('1')\nresource.User().update('1', {'name': 'test1'})\nresource.User().delete('1')\nresource.UserPhoneNum().get(('1', '10086'))\nresource.UserPhoneNum().delete(('1', '10086'))\n```\n\n\u5185\u90e8\u67e5\u8be2\u901a\u8fc7\u7ec4\u88c5dict\u6765\u5b9e\u73b0\u8fc7\u6ee4\u6761\u4ef6\uff0cfilter\u5728\u8868\u8fbe == \u6216 in \u5217\u8868\u65f6\uff0c\u53ef\u4ee5\u76f4\u63a5\u4f7f\u7528\u4e00\u7ea7\u5b57\u6bb5\u5373\u53ef\uff0c\u5982\nname\u7b49\u4e8etest\uff1a{'name': 'test'}\nid\u57281,2,3,4\u5185\uff1a{'id': ['1', '2', '3', '4']}\n\n\u66f4\u590d\u6742\u7684\u67e5\u8be2\u9700\u8981\u901a\u8fc7\u5d4c\u5957dict\u6765\u5b9e\u73b0[^ 5]\uff1a\n- \u7b80\u5355\u7ec4\u5408\uff1a{'\u5b57\u6bb5\u540d\u79f0': {'\u8fc7\u6ee4\u6761\u4ef61': '\u503c', '\u8fc7\u6ee4\u6761\u4ef62': '\u503c'}}\n\n- \u7b80\u5355\\$or+\u7ec4\u5408\u67e5\u8be2\uff1a{'\\$or': [{'\u5b57\u6bb5\u540d\u79f0': {'\u8fc7\u6ee4\u6761\u4ef6': '\u503c'}}, {'\u5b57\u6bb5\u540d\u79f0': {'\u8fc7\u6ee4\u6761\u4ef61': '\u503c', '\u8fc7\u6ee4\u6761\u4ef62': '\u503c'}}]}\n\n- \u7b80\u5355\\$and+\u7ec4\u5408\u67e5\u8be2\uff1a{'\\$and': [{'\u5b57\u6bb5\u540d\u79f0': {'\u8fc7\u6ee4\u6761\u4ef6': '\u503c'}}, {'\u5b57\u6bb5\u540d\u79f0': {'\u8fc7\u6ee4\u6761\u4ef61': '\u503c', '\u8fc7\u6ee4\u6761\u4ef62': '\u503c'}}]}\n\n- \u590d\u6742\\$and+\\$or+\u7ec4\u5408\u67e5\u8be2\uff1a\n  {'\\$and': [\n  \u200b               {'\\$or': [{'\u5b57\u6bb5\u540d\u79f0': '\u503c'}, {'\u5b57\u6bb5\u540d\u79f0': {'\u8fc7\u6ee4\u6761\u4ef61': '\u503c', '\u8fc7\u6ee4\u6761\u4ef62': '\u503c'}}]}, \n  \u200b               {'\u5b57\u6bb5\u540d\u79f0': {'\u8fc7\u6ee4\u6761\u4ef61': '\u503c', '\u8fc7\u6ee4\u6761\u4ef62': '\u503c'}}\n  ]}\n  \n- relationship\u590d\u6742\u67e5\u8be2(>=v1.3.6)\uff1a\n  \n  \u5047\u5b9a\u6709User(\u7528\u6237)\uff0cArticle(\u6587\u7ae0)\uff0cComment(\u8bc4\u8bba/\u7559\u8a00)\u8868\uff0cArticle.owner\u5f15\u7528User\uff0c Article.comments\u5f15\u7528Comment\uff0cComment.user\u5f15\u7528User\n  \n  \u67e5\u8be2A\u7528\u6237\u53d1\u8868\u7684\u6587\u7ae0\u4e2d\uff0c\u5b58\u5728B\u7528\u6237\u7684\u8bc4\u8bba\uff0c\u4e14\u8bc4\u8bba\u5185\u5bb9\u5305\u542b\u201d\u4f60\u597d\u201c\n  \n  Article.list({'owner_id': 'user_a', 'comments': {'content': {'ilike': '\u4f60\u597d', 'user': {'id': 'user_b'}}}})\n\n| \u8fc7\u6ee4\u6761\u4ef6 | \u503c\u7c7b\u578b          | \u542b\u4e49                                                           |\n| -------- | --------------- | -------------------------------------------------------------- |\n| like      | string         | \u6a21\u7cca\u67e5\u8be2\uff0c\u5305\u542b\u6761\u4ef6                                          |\n| ilike     | string         | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                             |\n| starts    | string         | \u6a21\u7cca\u67e5\u8be2\uff0c\u4ee5xxxx\u5f00\u5934                                           |\n| istarts   | string         | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                             |\n| ends      | string         | \u6a21\u7cca\u67e5\u8be2\uff0c\u4ee5xxxx\u7ed3\u5c3e                                           |\n| iends     | string         | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                             |\n| in        | list           | \u7cbe\u786e\u67e5\u8be2\uff0c\u6761\u4ef6\u5728\u5217\u8868\u4e2d                                         |\n| nin       | list           | \u7cbe\u786e\u67e5\u8be2\uff0c\u6761\u4ef6\u4e0d\u5728\u5217\u8868\u4e2d                                       |\n| eq        | \u6839\u636e\u5b57\u6bb5\u7c7b\u578b   | \u7b49\u4e8e                                                           |\n| ne        | \u6839\u636e\u5b57\u6bb5\u7c7b\u578b   | \u4e0d\u7b49\u4e8e                                                         |\n| lt        | \u6839\u636e\u5b57\u6bb5\u7c7b\u578b   | \u5c0f\u4e8e                                                           |\n| lte       | \u6839\u636e\u5b57\u6bb5\u7c7b\u578b   | \u5c0f\u4e8e\u7b49\u4e8e                                                       |\n| gt        | \u6839\u636e\u5b57\u6bb5\u7c7b\u578b   | \u5927\u4e8e                                                           |\n| gte       | \u6839\u636e\u5b57\u6bb5\u7c7b\u578b   | \u5927\u4e8e\u7b49\u4e8e                                                       |\n| nlike     | string         | \u6a21\u7cca\u67e5\u8be2\uff0c\u4e0d\u5305\u542b                                               |\n| nilike    | string         | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                             |\n| null      | \u4efb\u610f           | \u662fNULL\uff0c\u7b49\u540c\u4e8e{'eq': None}\uff0cnull\u4e3b\u8981\u63d0\u4f9bHTTP API\u4e2d\u4f7f\u7528                   |\n| nnull     | \u4efb\u610f           | \u4e0d\u662fNULL\uff0c\u7b49\u540c\u4e8e{'ne': None}\uff0cnnull\u4e3b\u8981\u63d0\u4f9bHTTP API\u4e2d\u4f7f\u7528                  |\n| hasany       | string/list[string] | *JSONB\u4e13\u7528*   \u5305\u542b\u4efb\u610fkey\uff0c\u5982['a','b', 'c'] hasany ['a','d'] |\n| hasall       | string/list[string] | *JSONB\u4e13\u7528*   \u5305\u542b\u6240\u6709key\uff0c\u5982['a','b', 'c'] hasall ['a','c'] |\n| within       | list/dict | *JSONB\u4e13\u7528*   \u88ab\u6307\u5b9ajson\u5305\u542b\u5728\u5185                             |\n| nwithin      | list/dict | *JSONB\u4e13\u7528*   \u4e0d\u88ab\u6307\u5b9ajson\u5305\u542b\u5728\u5185                           |\n| include      | list/dict | *JSONB\u4e13\u7528*   \u5305\u542b\u6307\u5b9a\u7684json                                 |\n| ninclude     | list/dict | *JSONB\u4e13\u7528*   \u4e0d\u5305\u542b\u6307\u5b9a\u7684json                               |\n\n\n\u8fc7\u6ee4\u6761\u4ef6\u53ef\u4ee5\u6839\u636e\u4e0d\u540c\u7684\u6570\u636e\u7c7b\u578b\u751f\u6210\u4e0d\u540c\u7684\u67e5\u8be2\u8bed\u53e5\uff0cvarchar\u7c7b\u578b\u7684in\u662f IN ('1', '2') , inet\u7c7b\u578b\u7684in\u662f<<=cidr\n\n\u4e00\u822c\u7c7b\u578b\u7684eq\u662fcol='value'\uff0cbool\u7c7b\u578b\u7684eq\u662fcol is TRUE\uff0c\u8be6\u89c1talos.db.filter_wrapper\n\n#### \u4e1a\u52a1api\u63a7\u5236\u7c7b\n\napi\u7684\u6a21\u5757\u4e3a\uff1acms.apps.user.api\n\nresource\u5904\u7406\u7684\u662fDB\u7684CRUD\u64cd\u4f5c\uff0c\u4f46\u5f80\u5f80\u4e1a\u52a1\u7c7b\u4ee3\u7801\u9700\u8981\u6709\u590d\u6742\u7684\u5904\u7406\u903b\u8f91\uff0c\u5e76\u4e14\u6d89\u53ca\u591a\u4e2aresource\u7c7b\u7684\u76f8\u4e92\u64cd\u4f5c\uff0c\u56e0\u6b64\u9700\u8981\u5c01\u88c5api\u5c42\u6765\u5904\u7406\u6b64\u7c7b\u903b\u8f91\uff0c\u6b64\u5904\u6211\u4eec\u793a\u4f8b\u6ca1\u6709\u590d\u6742\u903b\u8f91\uff0c\u76f4\u63a5\u6cbf\u7528\u5b9a\u4e49\u5373\u53ef\n\n```python\nUser = resource.User\nUserPhoneNum = resource.UserPhoneNum\n```\n\n#### Collection\u548cItem Controller\n\nController\u6a21\u5757\u4e3a\uff1acms.apps.user.controller\n\nController\u88ab\u8bbe\u8ba1\u5206\u7c7b\u4e3aCollection\u548cItem 2\u79cd\uff0c\u5206\u522b\u5bf9\u5e94RESTFul\u7684URL\u64cd\u4f5c\uff0c\u6211\u4eec\u5148\u770b\u4e00\u4e2a\u5e38\u89c1\u7684URL\u8bbe\u8ba1\u548c\u64cd\u4f5c\n\n```bash\nPOST   /v1/users    \u521b\u5efa\u7528\u6237\nGET    /v1/users    \u67e5\u8be2\u7528\u6237\u5217\u8868\nPATCH  /v1/users/1  \u66f4\u65b0\u7528\u62371\u7684\u4fe1\u606f\nDELETE /v1/users/1  \u5220\u9664\u7528\u62371\u7684\u4fe1\u606f\nGET    /v1/users/1  \u83b7\u53d6\u7528\u62371\u7684\u8be6\u60c5\n```\n\n\u6839\u636e\u5f53\u524d\u7684URL\u89c4\u5f8b\u6211\u4eec\u53ef\u4ee5\u5427\u521b\u5efa\u548c\u67e5\u8be2\u5217\u8868\u4f5c\u4e3a\u4e00\u4e2a\u5c01\u88c5\uff08CollectionController\uff09\uff0c\u800c\u66f4\u65b0\uff0c\u5220\u9664\uff0c\u83b7\u53d6\u8be6\u60c5\u4f5c\u4e3a\u4e00\u4e2a\u5c01\u88c5\uff08ItemController\uff09\uff0c\u800c\u540c\u6837\u7684\uff0c\u5bf9\u4e8e\u8fd9\u6837\u7684\u6807\u51c6\u64cd\u4f5c\uff0ctalos\u540c\u6837\u63d0\u4f9b\u4e86\u9b54\u6cd5\u822c\u7684\u5b9a\u4e49\n\n```python\nclass CollectionUser(CollectionController):\n    name = 'cms.users'\n    resource = api.User\n\nclass ItemUser(ItemController):\n    name = 'cms.user'\n    resource = api.User\n```\n\n#### route\u8def\u7531\u6620\u5c04\n\nroute\u6a21\u5757\u4e3a\uff1acms.apps.user.route\n\n\u63d0\u4f9b\u4e86Controller\u540e\uff0c\u6211\u4eec\u8fd8\u9700\u8981\u5c06\u5176\u4e0eURL\u8def\u7531\u8fdb\u884c\u6620\u5c04\u624d\u80fd\u8c03\u7528\uff0croute\u6a21\u5757\u4e2d\uff0c\u5fc5\u987b\u6709add_routes\u51fd\u6570\uff0c\u6ce8\u518capp\u7684\u65f6\u5019\u4f1a\u9ed8\u8ba4\u5bfb\u627e\u8fd9\u4e2a\u51fd\u6570\u6765\u6ce8\u518c\u8def\u7531\n\n```python\ndef add_routes(api):\n    api.add_route('/v1/users', controller.CollectionUser())\n    api.add_route('/v1/users/{rid}', controller.ItemUser())\n```\n\n#### \u914d\u7f6e\u542f\u52a8\u52a0\u8f7dapp\n\n\u6211\u4eec\u5728\u5f15\u5bfc\u5f00\u59cb\u65f6\u521b\u5efa\u7684\u9879\u76ee\u914d\u7f6e\u6587\u4ef6\u5b58\u653e\u5728./etc\u4e2d\uff0c\u6240\u4ee5\u6211\u4eec\u7684\u914d\u7f6e\u6587\u4ef6\u5728./etc/cms.conf\uff0c\u4fee\u6539\n\n```javascript\n...\n\"application\": {\n        \"names\": [\n            \"cms.apps.user\"]\n},\n...\n```\n\n#### \u542f\u52a8\u8c03\u8bd5\u6216\u90e8\u7f72\n\n\u5728\u6e90\u7801\u76ee\u5f55\u4e2d\u6709server\u5305\uff0c\u5176\u4e2dsimple_server\u662f\u7528\u4e8e\u5f00\u53d1\u8c03\u8bd5\u7528\uff0c\u4e0d\u5efa\u8bae\u5728\u751f\u4ea7\u4e2d\u4f7f\u7528\n\npython simple_server.py\n\n#### \u6d4b\u8bd5API\n\n\u542f\u52a8\u540e\u6211\u4eec\u7684\u670d\u52a1\u5df2\u7ecf\u53ef\u4ee5\u5bf9\u5916\u8f93\u51fa\u5566\uff01\n\n\u90a3\u4e48\u6211\u4eec\u7684API\u5230\u5e95\u63d0\u4f9b\u4e86\u4ec0\u4e48\u6837\u7684\u80fd\u529b\u5462\uff1f\u6211\u4eec\u4ee5user\u4f5c\u4e3a\u793a\u4f8b\u5c55\u793a\n\n\u521b\u5efa\n\n```\nPOST /v1/users\nContent-Type: application/json;charset=UTF-8\nHost: 127.0.0.1:9002\n\n{\n    \"id\": \"1\",\n    \"name\": \"test\"\n}\n```\n\n\u67e5\u8be2\u5217\u8868\n\n```\nGET /v1/users\nHost: 127.0.0.1:9002\n\n{\n    \"count\": 1,\n    \"data\": [\n        {\n            \"id\": \"1\",\n            \"name\": \"test\"\n        }\n    ]\n}\n```\n\n\u5173\u4e8e\u67e5\u8be2\u5217\u8868\uff0c\u6211\u4eec\u63d0\u4f9b\u4e86\u5f3a\u5927\u7684\u67e5\u8be2\u80fd\u529b\uff0c\u53ef\u4ee5\u6ee1\u8db3\u5927\u90e8\u5206\u7684\u67e5\u8be2\u573a\u666f\n\n\u83b7\u53d6**\u5217\u8868(\u67e5\u8be2)\u7684\u63a5\u53e3**\u53ef\u4ee5\u4f7f\u7528Query\u53c2\u6570\u8fc7\u6ee4\uff0c\u4f7f\u7528\u8fc7\u6ee4\u5b57\u6bb5=xxx \u6216 \u5b57\u6bb5__\u67e5\u8be2\u6761\u4ef6=xxx\u65b9\u5f0f\u4f20\u9012\n\n- **\u8fc7\u6ee4\u6761\u4ef6**\n\n     eg.\n\n     ```bash\n     # \u67e5\u8be2name\u5b57\u6bb5\u7b49\u4e8eabc\n     name=abc\n     # \u67e5\u8be2name\u5b57\u6bb5\u5305\u542babc\n     name__icontains=abc\n     # \u67e5\u8be2name\u5b57\u6bb5\u5728\u5217\u8868[a, b, c]\u503c\u5185\n     name=a&name=b&name=c \n     # \u6216 \n     name__in=a&name__in=b&name__in=c\n     # \u67e5\u8be2name\u5b57\u6bb5\u5728\u5217\u8868\u503c\u5185\n     name[0]=a&name[1]=b&name[2]=c \n     # \u6216 \n     name__in[0]=a&name__in[1]=b&name__in[2]=c\n     ```\n\n     \u540c\u65f6\u652f\u6301\u5168\u62fc\u6761\u4ef6\u548c\u7f29\u5199\u6761\u4ef6\u67e5\u8be2\uff1a\n\n\n| \u5168\u62fc\u6761\u4ef6     | \u7f29\u5199\u6761\u4ef6 | \u542b\u4e49                                                         |\n| ------------ | -------- | ------------------------------------------------------------ |\n| N/A          |          | \u7cbe\u786e\u67e5\u8be2\uff0c\u5b8c\u5168\u7b49\u4e8e\u6761\u4ef6\uff0c\u5982\u679c\u591a\u4e2a\u6b64\u6761\u4ef6\u51fa\u73b0\uff0c\u5219\u8ba4\u4e3a\u6761\u4ef6\u5728\u5217\u8868\u4e2d |\n| contains     | like     | \u6a21\u7cca\u67e5\u8be2\uff0c\u5305\u542b\u6761\u4ef6                                           |\n| icontains    | ilike    | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                           |\n| startswith   | starts   | \u6a21\u7cca\u67e5\u8be2\uff0c\u4ee5xxxx\u5f00\u5934                                         |\n| istartswith  | istarts  | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                           |\n| endswith     | ends     | \u6a21\u7cca\u67e5\u8be2\uff0c\u4ee5xxxx\u7ed3\u5c3e                                         |\n| iendswith    | iends    | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                           |\n| in           | in       | \u7cbe\u786e\u67e5\u8be2\uff0c\u6761\u4ef6\u5728\u5217\u8868\u4e2d                                       |\n| notin        | nin      | \u7cbe\u786e\u67e5\u8be2\uff0c\u6761\u4ef6\u4e0d\u5728\u5217\u8868\u4e2d                                     |\n| equal        | eq       | \u7b49\u4e8e                                                         |\n| notequal     | ne       | \u4e0d\u7b49\u4e8e                                                       |\n| less         | lt       | \u5c0f\u4e8e                                                         |\n| lessequal    | lte      | \u5c0f\u4e8e\u7b49\u4e8e                                                     |\n| greater      | gt       | \u5927\u4e8e                                                         |\n| greaterequal | gte      | \u5927\u4e8e\u7b49\u4e8e                                                     |\n| excludes     | nlike    | \u6a21\u7cca\u67e5\u8be2\uff0c\u4e0d\u5305\u542b                                             |\n| iexcludes    | nilike   | \u540c\u4e0a\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199                                           |\n| null         | null     | \u662fNULL                                                       |\n| notnull      | nnull    | \u4e0d\u662fNULL                                                     |\n| hasany       | hasany   | *JSONB\u4e13\u7528*   \u5305\u542b\u4efb\u610fkey\uff0c\u5982['a','b', 'c'] hasany ['a','d'] |\n| hasall       | hasall   | *JSONB\u4e13\u7528*   \u5305\u542b\u6240\u6709key\uff0c\u5982['a','b', 'c'] hasall ['a','c'] |\n| within       | within   | *JSONB\u4e13\u7528*   \u88ab\u6307\u5b9ajson\u5305\u542b\u5728\u5185                             |\n| nwithin      | nwithin  | *JSONB\u4e13\u7528*   \u4e0d\u88ab\u6307\u5b9ajson\u5305\u542b\u5728\u5185                           |\n| include      | include  | *JSONB\u4e13\u7528*   \u5305\u542b\u6307\u5b9a\u7684json                                 |\n| ninclude     | ninclude | *JSONB\u4e13\u7528*   \u4e0d\u5305\u542b\u6307\u5b9a\u7684json                               |\n\n\n\n\u5b57\u6bb5\u652f\u6301\uff1a\u666e\u901acolumn\u5b57\u6bb5\u3001relationship\u5b57\u6bb5(single or list)\u3001JSONB[^ 4]\n\n\u5047\u8bbe\u6709API\u5bf9\u5e94\u5982\u4e0b\u8868\u5b57\u6bb5\n\n```python\nclass User(Base, DictBase):\n    __tablename__ = 'user'\n\n    id = Column(String(36), primary_key=True)\n    name = Column(String(36), nullable=False)\n    department_id = Column(ForeignKey(u'department.id'), nullable=False)\n    items = Column(JSONB, nullable=False)\n\n    department = relationship(u'Department', lazy=False)\n    addresses = relationship(u'Address', lazy=False, back_populates=u'user', uselist=True, viewonly=True)\n    \nclass Address(Base, DictBase):\n    __tablename__ = 'address'\n\n    id = Column(String(36), primary_key=True)\n    location = Column(String(36), nullable=False)\n    user_id = Column(ForeignKey(u'user.id'), nullable=False)\n    items = Column(JSONB, nullable=False)\n\n    user = relationship(u'User', lazy=True)\n    \nclass Department(Base, DictBase):\n    __tablename__ = 'department'\n\n    id = Column(String(36), primary_key=True)\n    name = Column(String(36), nullable=False)\n    user_id = Column(ForeignKey(u'user.id'), nullable=False)\n```\n\n\u53ef\u4ee5\u8fd9\u6837\u6784\u9020\u8fc7\u6ee4\u6761\u4ef6\n\n/v1/users?name=\u5c0f\u660e\n\n/v1/users?department.name=\u4e1a\u52a1\u90e8\n\n/v1/users?addresses.location__icontains=\u5e7f\u4e1c\u7701\n\n/v1/users?addresses.items.key__icontains=temp\n\n/v1/users?items.0.age=60 # items = [{\"age\": 60, \"sex\": \"male\"}, {...}]\n\n/v1/users?items.age=60 # items = {\"age\": 60, \"sex\": \"male\"}\n\n> v1.2.0  \u8d77\u4e0d\u652f\u6301\u7684column\u6216condition\u4f1a\u89e6\u53d1ResourceBase._unsupported_filter(query, idx, name, op, value)\u51fd\u6570\uff0c\u51fd\u6570\u9ed8\u8ba4\u8fd4\u56de\u53c2\u6570query\u4ee5\u5ffd\u7565\u672a\u652f\u6301\u7684\u8fc7\u6ee4(\u517c\u5bb9\u4ee5\u524d\u7248\u672c\u884c\u4e3a)\uff0c\u7528\u6237\u53ef\u4ee5\u81ea\u884c\u91cd\u8f7d\u51fd\u6570\u4ee5\u5b9e\u73b0\u81ea\u5b9a\u4e49\u884c\u4e3a\n>\n> v1.2.2  unsupported_filter\u4f1a\u9ed8\u8ba4\u6784\u9020\u4e00\u4e2a\u7a7a\u67e5\u8be2\u96c6\uff0c\u5373\u4e0d\u652f\u6301\u7684column\u6216condition\u4f1a\u81f4\u4f7f\u8fd4\u56de\u7a7a\u7ed3\u679c\n\n\n\n\n- **\u504f\u79fb\u91cf\u4e0e\u6570\u91cf\u9650\u5236**\n\n     \u67e5\u8be2\u8fd4\u56de\u5217\u8868\u65f6\uff0c\u901a\u5e38\u9700\u8981\u6307\u5b9a\u504f\u79fb\u91cf\u4ee5\u53ca\u6570\u91cf\u9650\u5236\n\n     eg. \n\n     ```bash\n     __offset=10&__limit=20\n     ```\n\n     \u4ee3\u8868\u53d6\u504f\u79fb\u91cf10\uff0c\u9650\u523620\u6761\u7ed3\u679c\n\n- **\u6392\u5e8f**\n\n     \u6392\u5e8f\u5bf9\u67d0\u4e9b\u573a\u666f\u975e\u5e38\u91cd\u8981\uff0c\u53ef\u4ee5\u514d\u53bb\u5ba2\u6237\u7aef\u5f88\u591a\u5de5\u4f5c\u91cf\n\n     ```bash\n     __orders=name,-env_code\n     ```\n\n     \u591a\u4e2a\u5b57\u6bb5\u6392\u5e8f\u4ee5\u82f1\u6587\u9017\u53f7\u95f4\u9694\uff0c\u9ed8\u8ba4\u9012\u589e\uff0c\u82e5\u5b57\u6bb5\u524d\u9762\u6709-\u51cf\u53f7\u5219\u4ee3\u8868\u9012\u51cf\n\n     ```\n       PS\uff1a\u6211\u53ef\u4ee5\u4f7f\u7528+name\u4ee3\u8868\u9012\u589e\u5417\uff1f\n     \n       \u53ef\u4ee5\uff0c\u4f46\u662fHTTP URL\u4e2d+\u53f7\u5b9e\u9645\u4e0a\u7684\u7a7a\u683c\u7684\u7f16\u7801\uff0c\u5982\u679c\u4f20\u9012__orders=+name,-env_code\uff0c\u5728HTTP\u4e2d\u5b9e\u9645\u7b49\u4ef7\u4e8e__orders=\u7a7a\u683cname,-env_code, \u65e0\u7b26\u53f7\u9ed8\u8ba4\u9012\u589e\uff0c\u56e0\u6b64\u65e0\u9700\u591a\u4f20\u9012\u4e00\u4e2a+\u53f7\uff0c\u4f20\u9012\u5b57\u6bb5\u5373\u53ef\n     ```\n\n- **\u5b57\u6bb5\u9009\u62e9**\n\n     \u63a5\u53e3\u8fd4\u56de\u4e2d\uff0c\u5982\u679c\u5b57\u6bb5\u4fe1\u606f\u592a\u591a\uff0c\u4f1a\u5bfc\u81f4\u4f20\u8f93\u7f13\u6162\uff0c\u5e76\u4e14\u9700\u8981\u5ba2\u6237\u7aef\u5360\u7528\u5927\u91cf\u5185\u5b58\u5904\u7406\n\n     ```bash\n     __fields=name,env_code\n     ```\n\n     \u53ef\u4ee5\u6307\u5b9a\u8fd4\u56de\u9700\u8981\u7684\u5b57\u6bb5\u4fe1\u606f\uff0c\u6216\u8005\u5e72\u8106\u4e0d\u6307\u5b9a\uff0c\u83b7\u53d6\u6240\u6709\u670d\u52a1\u5668\u652f\u6301\u7684\u5b57\u6bb5\n\n\n### \u8fdb\u9636\u5f00\u53d1\n\n#### \u7528\u6237\u8f93\u5165\u6821\u9a8c\n\n\u7528\u6237\u8f93\u5165\u7684\u6570\u636e\uff0c\u4e0d\u4e00\u5b9a\u662f\u5b8c\u5168\u6b63\u786e\u7684\uff0c\u6bcf\u4e2a\u6570\u636e\u90fd\u9700\u8981\u6821\u9a8c\u540e\u624d\u80fd\u8fdb\u884c\u5b58\u50a8\u548c\u5904\u7406\uff0c\u5728\u4e0a\u9762\u5df2\u7ecf\u63d0\u5230\u8fc7\u4f7f\u7528ColumnValidator\u6765\u8fdb\u884c\u6570\u636e\u6821\u9a8c\uff0c\u8fd9\u91cc\u4e3b\u8981\u662f\u89e3\u91ca\u8be6\u7ec6\u7684\u6821\u9a8c\u89c4\u5219\u548c\u884c\u4e3a\n\n1. ColumnValidator\u88ab\u9ed8\u8ba4\u96c6\u6210\u5728ResourceBase\u4e2d\uff0c\u6240\u4ee5\u4f1a\u81ea\u52a8\u8fdb\u884c\u6821\u9a8c\u5224\u65ad\n\n2. \u672a\u5b9a\u4e49_validate\u65f6\uff0c\u5c06\u4e0d\u542f\u7528\u6821\u9a8c\uff0c\u4fe1\u4efb\u6240\u6709\u8f93\u5165\u6570\u636e\n\n3. \u672a\u5b9a\u4e49\u7684\u5b57\u6bb5\u5728\u6e05\u6d17\u9636\u6bb5\u4f1a\u88ab\u5ffd\u7565\n\n4. \u6821\u9a8c\u7684\u5173\u952e\u51fd\u6570\u4e3aResourceBase.validate\n\n   ```python\n   @classmethod\n   def validate(cls, data, situation, orm_required=False, validate=True, rule=None):\n       \"\"\"\n       \u9a8c\u8bc1\u5b57\u6bb5\uff0c\u5e76\u8fd4\u56de\u6e05\u6d17\u540e\u7684\u6570\u636e\n       \n       * \u5f53validate=False\uff0c\u4e0d\u4f1a\u5bf9\u6570\u636e\u8fdb\u884c\u6821\u9a8c\uff0c\u4ec5\u8fd4\u56deORM\u9700\u8981\u6570\u636e\n       * \u5f53validate=True\uff0c\u5bf9\u6570\u636e\u8fdb\u884c\u6821\u9a8c\uff0c\u5e76\u6839\u636eorm_required\u8fd4\u56de\u5168\u90e8/ORM\u6570\u636e\n       \n       :param data: \u6e05\u6d17\u524d\u7684\u6570\u636e\n       :type data: dict\n       :param situation: \u5f53\u524d\u573a\u666f\n       :type situation: string\n       :param orm_required: \u662f\u5426ORM\u9700\u8981\u7684\u6570\u636e(ORM\u5373Model\u8868\u5b9a\u4e49\u7684\u5b57\u6bb5)\n       :type orm_required: bool\n       :param validate: \u662f\u5426\u9a8c\u8bc1\u89c4\u5219\n       :type validate: bool\n       :param rule: \u89c4\u5219\u914d\u7f6e\n       :type rule: dict\n       :returns: \u8fd4\u56de\u6e05\u6d17\u540e\u7684\u6570\u636e\n       :rtype: dict\n       \"\"\"\n   ```\n\n   *validate_on\u4e3a\u4ec0\u4e48\u662f\u586b\u5199\uff1acreate:M\u6216\u8005update:M\uff0c\u56e0\u4e3avalidate\u6309\u7167\u51fd\u6570\u540d\u8fdb\u884c\u573a\u666f\u5224\u5b9a\uff0c\u5728ResourceBase.create\u51fd\u6570\u4e2d\uff0c\u9ed8\u8ba4\u5c06situation\u7ed1\u5b9a\u5728\u5f53\u524d\u51fd\u6570\uff0c\u5373 'create'\uff0cupdate\u540c\u7406\uff0c\u800cM\u4ee3\u8868\u5fc5\u9009\uff0cO\u4ee3\u8868\u53ef\u9009*\n\n5. \u5f53\u524d\u5feb\u901f\u6821\u9a8c\u89c4\u5219rule_type\u4e0d\u80fd\u6ee1\u8db3\u65f6\uff0c\u8bf7\u4f7f\u7528Validator\u5bf9\u8c61\uff0c\u5185\u7f6eValidator\u5bf9\u8c61\u4e0d\u80fd\u6ee1\u8db3\u9700\u6c42\u65f6\uff0c\u53ef\u4ee5\u5b9a\u5236\u81ea\u5df1\u7684Validator\uff0cValidator\u7684\u5b9a\u4e49\u9700\u8981\u6ee1\u8db32\u70b9\uff1a\n\n   \u4eceNullValidator\u4e2d\u7ee7\u627f\n\n   \u91cd\u5199validate\u51fd\u6570\uff0c\u51fd\u6570\u63a5\u53d7\u4e00\u4e2a\u53c2\u6570\uff0c\u5e76\u4e14\u8fd4\u56deTrue\u4f5c\u4e3a\u901a\u8fc7\u6821\u9a8c\uff0c\u8fd4\u56de\u9519\u8bef\u5b57\u7b26\u4e32\u4ee3\u8868\u6821\u9a8c\u5931\u8d25\n\n6. Converter\u540c\u4e0a\n\n#### \u591a\u6570\u636e\u5e93\u652f\u6301 [^ 7]\n\n\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u9879\u76ee\u53ea\u4f1a\u751f\u6210\u4e00\u4e2a\u6570\u636e\u5e93\u8fde\u63a5\u6c60\uff1a\u5bf9\u5e94\u914d\u7f6e\u9879CONF.db.xxxx\uff0c\u82e5\u9700\u8981\u591a\u4e2a\u6570\u636e\u5e93\u8fde\u63a5\u6c60\uff0c\u5219\u9700\u8981\u624b\u52a8\u6307\u5b9a\u914d\u7f6e\u6587\u4ef6\n\n```\n\"dbs\": {\n    \"read_only\": {\n        \"connection\": \"sqlite:///tests/a.sqlite3\"\n    },\n    \"other_cluster\": {\n        \"connection\": \"sqlite:///tests/b.sqlite3\"\n    }\n},\n```\n\n\u4f7f\u7528\u65b9\u5f0f\u4e5f\u7b80\u5355\uff0c\u5982\u4e0b\uff0c\u751f\u6548\u4f18\u5148\u7ea7\u4e3a\uff1a\u5b9e\u4f8b\u5316\u53c2\u6570 > \u7c7b\u5c5e\u6027orm_pool > defaultPool\n\n```python\n# 1. \u5728\u7c7b\u5c5e\u6027\u4e2d\u6307\u5b9a \nclass Users(ResourceBase):\n    orm_meta = models.Users\n    orm_pool = pool.POOLS.read_only\n    \n# 2. \u5b9e\u4f8b\u5316\u65f6\u6307\u5b9a\nUsers(dbpool=pool.POOLS.readonly)\n\n# 3. \u82e5\u90fd\u4e0d\u6307\u5b9a\uff0c\u9ed8\u8ba4\u4f7f\u7528defaultPool\uff0c\u5373CONF.db\u914d\u7f6e\u7684\u8fde\u63a5\u6c60\n```\n\n\n\n\n#### DB Hook\u64cd\u4f5c\n\n##### \u7b80\u5355hooks\n\n\u5728db\u521b\u5efa\u4e00\u4e2a\u8bb0\u5f55\u65f6\uff0c\u5047\u8bbe\u5e0c\u671bid\u662f\u81ea\u52a8\u751f\u6210\u7684UUID\uff0c\u901a\u5e38\u8fd9\u610f\u5473\u7740\u6211\u4eec\u4e0d\u5f97\u4e0d\u91cd\u5199create\u51fd\u6570\uff1a\n\n```python\nclass User(ResourceBase):\n    orm_meta = models.User\n    _primary_keys = 'id'\n    \n    def create(self, resource, validate=True, detail=True):\n        resource['id'] = uuid.uuid4().hex\n        super(User, self).create(resource, validate=validate, detail=validate)\n```\n\n\u8fd9\u6837\u7684\u64cd\u4f5c\u5bf9\u4e8e\u6211\u4eec\u800c\u8a00\u662f\u5f88\u7b28\u91cd\u7684\uff0c\u751a\u81f3create\u7684\u5b9e\u73b0\u6bd4\u8f83\u590d\u6742\uff0c\u8ba9\u6211\u4eec\u4e0d\u5e0c\u671b\u5230create\u91cc\u9762\u53bb\u52a0\u8fd9\u4e9b\u4e0d\u662f\u90a3\u4e48\u5173\u952e\u7684\u4ee3\u7801\uff0c\u5bf9\u4e8e\u8fd9\u4e9b\u64cd\u4f5c\uff0ctalos\u5206\u6210\u4e862\u79cd\u573a\u666f\uff0c_before_create, _addtional_create\uff0c\u6839\u636e\u540d\u79f0\u6211\u4eec\u80fd\u77e5\u9053\uff0c\u5b83\u4eec\u5206\u522b\u4ee3\u8868\n\ncreate\u6267\u884c\u5f00\u59cb\u524d\uff1a\u5e38\u7528\u4e8e\u4e00\u4e9b\u6570\u636e\u7684\u81ea\u52a8\u586b\u5145\n\ncreate\u6267\u884c\u540e\u4f46\u672a\u63d0\u4ea4\uff1a\u5e38\u7528\u4e8e\u5f3a\u4e8b\u52a1\u63a7\u5236\u7684\u64cd\u4f5c\uff0c\u53ef\u4ee5\u4f7f\u7528\u540c\u4e00\u4e2a\u4e8b\u52a1\u8fdb\u884c\u64cd\u4f5c\u4ee5\u4fbf\u4e00\u8d77\u63d0\u4ea4\u6216\u56de\u6eda\n\n\u540c\u7406\u8fd8\u6709update\uff0cdelete\n\n\u540c\u6837\u7684list\u548ccount\u90fd\u6709_addtional_xxxx\u94a9\u5b50\n\n##### \u52a8\u6001hooks\n\n\u4ee5\u4e0a\u7684hooks\u90fd\u662f\u7c7b\u6210\u5458\u51fd\u6570\u4ee3\u7801\u5b9a\u4e49\u7684\uff0c\u5f53\u4f7f\u7528\u8005\u60f3\u8981\u4e34\u65f6\u589e\u52a0\u4e00\u4e2ahook\u7684\u65f6\u5019\u5462\uff0c\u6216\u8005\u6839\u636e\u67d0\u4e2a\u6761\u4ef6\u5224\u65ad\u662f\u5426\u4f7f\u7528\u4e00\u4e2ahook\u65f6\uff0c\u6211\u4eec\u9700\u8981\u4e00\u79cd\u66f4\u52a8\u6001\u7684hook\u6765\u652f\u6301\uff0c\u76ee\u524d\u53ea\u6709list\u548ccount\u652f\u6301\u6b64\u7c7bhooks\n\nlist,count\u7684hook\u7684\u51fd\u6570\u5b9a\u4e49\u4e3a\uff1afunction(query, filters)\uff0c\u9700\u8981return \u5904\u7406\u540e\u7684query\n\neg. self.list(hooks=[lambda q,f: return q])\n\n##### \u81ea\u5b9a\u4e49query\n\n\u5728\u66f4\u590d\u6742\u7684\u573a\u666f\u4e0b\u6211\u4eec\u5c01\u88c5\u7684\u64cd\u4f5c\u51fd\u6570\u53ef\u80fd\u65e0\u6cd5\u8fbe\u5230\u76ee\u7684\uff0c\u6b64\u65f6\u53ef\u4ee5\u4f7f\u7528\u5e95\u5c42\u7684SQLAlchemy Query\u5bf9\u8c61\u6765\u8fdb\u884c\u5904\u7406\uff0c\u6bd4\u5982\u5728PG\u4e2dINET\u7c7b\u578b\u7684\u6bd4\u8f83\u64cd\u4f5c\uff1a\n\n\u4e00\u4e2a\u573a\u666f\uff1a\u6211\u4eec\u4e0d\u5e0c\u671b\u7528\u6237\u65b0\u589e\u7684\u5b50\u7f51\u4fe1\u606f\u4e0e\u73b0\u6709\u5b50\u7f51\u91cd\u53e0\n\n```python\nquery = self._get_query(session)\nquery = query.filter(self.orm_meta.cidr.op(\">>\")(\n    subnet['cidr']) | self.orm_meta.cidr.op(\"<<\")(subnet['cidr']))\nif query.one_or_none():\n    raise ConflictError()\n```\n\n#### \u4f1a\u8bdd\u91cd\u7528\u548c\u4e8b\u52a1\u63a7\u5236\n\n\u5728talos\u4e2d\uff0c\u6bcf\u4e2aResourceBase\u5bf9\u8c61\u90fd\u53ef\u4ee5\u7533\u8bf7\u4f1a\u8bdd\u548c\u4e8b\u52a1\uff0c\u800c\u4e14\u53ef\u4ee5\u63a5\u53d7\u4e00\u4e2a\u5df2\u6709\u7684\u4f1a\u8bdd\u548c\u4e8b\u52a1\u5bf9\u8c61\uff0c\u5728\u4f7f\u7528\u5b8c\u6bd5\u540etalos\u4f1a\u81ea\u52a8\u5e2e\u52a9\u4f60\u8fdb\u884c\u56de\u6eda/\u63d0\u4ea4/\u5173\u95ed\uff0c\u8fd9\u5f97\u76ca\u4e0epython\u7684with\u5b50\u53e5\n\n```python\nu = User()\nwith u.transaction() as session:\n    u.update(...)\n    # \u4e8b\u52a1\u91cd\u7528, \u53ef\u4ee5\u67e5\u8be2\u548c\u53d8\u66f4\u64cd\u4f5c, with\u5b50\u53e5\u7ed3\u675f\u4f1a\u81ea\u52a8\u63d0\u4ea4\uff0c\u5f02\u5e38\u4f1a\u81ea\u52a8\u56de\u6eda\n    UserPhone(transaction=session).delete(...)\n    UserPhone(transaction=session).list(...)\nwith u.get_session() as session:\n    # \u4f1a\u8bdd\u91cd\u7528, \u53ef\u4ee5\u67e5\u8be2\n    UserPhone(session=session).list(...)\n```\n\n#### \u7f13\u5b58\n\n##### \u914d\u7f6e\u548c\u4f7f\u7528\n\n\u9ed8\u8ba4\u914d\u7f6e\u4e3a\u8fdb\u7a0b\u5185\u5b58\uff0c\u8d85\u65f660\u79d2\n\n```python\n'cache': {\n        'type': 'dogpile.cache.memory',\n        'expiration_time': 60\n}\n```\n\n\u7f13\u5b58\u540e\u7aef\u652f\u6301\u53d6\u51b3\u4e8edogpile\u6a21\u5757\uff0c\u53ef\u4ee5\u652f\u6301\u5e38\u89c1\u7684memcache\uff0credis\u7b49\n\n\u5982\uff1aredis\n\n```python\n\"cache\": {\n        \"type\": \"dogpile.cache.redis\",\n        \"expiration_time\": 6,\n        \"arguments\": {\n            \"host\": \"127.0.0.1\",\n            \"password\": \"football\",\n            \"port\": 1234,\n            \"db\": 0,\n            \"redis_expiration_time\": 60,\n            \"distributed_lock\": true\n        }\n    }\n```\n\n\u4f7f\u7528\u65b9\u5f0f\n\n```python\nfrom talos.common import cache\n\ncache.get(key, exipres=None)\ncache.set(key, value)\ncache.validate(value)\ncache.get_or_create(key, creator, expires=None)\ncache.delete(key)\n```\n\n\n\n#### \u5f02\u6b65\u4efb\u52a1\n\n##### \u5b9a\u4e49\u5f02\u6b65\u4efb\u52a1\n\n> talos >=1.3.0 send_callback\u51fd\u6570\uff0c\u79fb\u9664\u4e86timeout\uff0c\u589e\u52a0\u4e86request_context\uff0c\u4e3arequests\u8bf7\u6c42\u53c2\u6570\u7684options\u7684\u5b57\u5178\uff0ceg.{'timeout': 3}\n\n> talos >=1.3.0 \u56de\u8c03\u51fd\u6570\u53c2\u6570\uff0c\u79fb\u9664\u4e86request\u548cresponse\u7684\u5f3a\u5236\u53c2\u6570\u5b9a\u4e49\uff0c\u4fdd\u7559data\u548curl\u6a21\u677f\u5f3a\u5236\u53c2\u6570\uff0c\u5982\u679ccallback(with_request=True)\uff0c\u5219\u56de\u8c03\u51fd\u6570\u9700\u5b9a\u4e49\u5982\u4e0b\uff0cwith_response\u540c\u7406\n>\n> @callback('/add/{x}/{y}', with_request=True):\n>\n> def add(data, x, y, request):\n>\n> \u200b    pass\n\n> talos >=1.3.0 \u88abcallback\u88c5\u9970\u7684\u56de\u8c03\u51fd\u6570\uff0c\u5747\u652f\u6301\u672c\u5730\u8c03\u7528/\u5feb\u901f\u8fdc\u7a0b\u8c03\u7528/send_callback\u8c03\u7528\n>\n> talos <1.3.0\u652f\u6301\u672c\u5730\u8c03\u7528/send_callback\u8c03\u7528\n>\n>     \u672c\u5730\u8c03\u7528\uff1a\n>     add(data, x, y)\uff0c\u53ef\u4ee5\u4f5c\u4e3a\u666e\u901a\u672c\u5730\u51fd\u6570\u8c03\u7528(\u6ce8\uff1a\u5ba2\u6237\u7aef\u8fd0\u884c\uff09\n>        \n>     send_callback\u8fdc\u7a0b\u8c03\u7528\u65b9\u5f0f(x,y\u53c2\u6570\u5fc5\u987b\u7528kwargs\u5f62\u5f0f\u4f20\u53c2)\uff1a\n>     send_callback(None, add, data, x=1, y=7)\n>        \n>     \u5feb\u901f\u8fdc\u7a0b\u8c03\u7528\uff1a\n>     \u652f\u6301\u8bbe\u7f6econtext\uff0cbaseurl\u8fdb\u884c\u8c03\u7528\uff0ccontext\u4e3arequests\u5e93\u7684\u989d\u5916\u53c2\u6570\uff0c\u6bd4\u5982headers\uff0ctimeout\uff0cverify\u7b49\uff0cbaseurl\u9ed8\u8ba4\u4e3a\u914d\u7f6e\u9879\u7684public_endpoint(x,y\u53c2\u6570\u5fc5\u987b\u7528kwargs\u5f62\u5f0f\u4f20\u53c2)\n>        \n>     test.remote({'val': '123'}, x=1, y=7)\n>     test.context(timeout=10, params={'search': 'me'}).remote({'val': '123'}, x=1, y=7)\n>     test.context(timeout=10).baseurl('http://clusterip.of.app.com').remote({'val': '123'}, x=1, y=7)\n\n\u5efa\u7acbworkers.app_name.tasks.py\u7528\u4e8e\u7f16\u5199\u8fdc\u7a0b\u4efb\u52a1\n\u5efa\u7acbworkers.app_name.callback.py\u7528\u4e8e\u7f16\u5199\u8fdc\u7a0b\u8c03\u7528\ntask.py\u4efb\u52a1\u793a\u4f8b\n\n```python\nfrom talos.common import celery\nfrom talos.common import async_helper\nfrom cms.workers.app_name import callback\n@celery.app.task\ndef add(data, task_id):\n    result = {'result': data['x'] + data['y']}\n\n    # \u8fd9\u91cc\u8fd8\u53ef\u4ee5\u901a\u77e5\u5176\u4ed6\u9644\u52a0\u4efb\u52a1,\u5f53\u9700\u8981\u672c\u6b21\u7684\u4e00\u4e9b\u8ba1\u7b97\u7ed3\u679c\u6765\u542f\u52a8\u4e8c\u6b21\u4efb\u52a1\u65f6\u4f7f\u7528\n    # \u63a5\u53d7\u53c2\u6570\uff1atask\u8c03\u7528\u51fd\u6570\u8def\u5f84 & \u51fd\u6570\u547d\u540d\u53c2\u6570(dict)\n    # async_helper.send_task('cms.workers.app_name.tasks.other_task', kwargs={'result': result, 'task_id': task_id})\n\n   # \u5f02\u6b65\u4efb\u52a1\u4e2d\u9ed8\u8ba4\u4e0d\u542f\u7528\u6570\u636e\u5e93\u8fde\u63a5\uff0c\u56e0\u6b64\u9700\u8981\u4f7f\u7528\u8fdc\u7a0b\u8c03\u7528callback\u65b9\u5f0f\u8fdb\u884c\u6570\u636e\u8bfb\u53d6\u548c\u56de\u5199\n   # \u5982\u679c\u60f3\u8981\u4f7f\u7528db\u529f\u80fd\uff0c\u9700\u8981\u4fee\u6539cms.server.celery_worker\u6587\u4ef6\u7684\u4ee3\u7801,\u79fb\u9664 # base.initialize_db()\u7684\u6ce8\u91ca\u7b26\u53f7\n\n   # send callback\u7684\u53c2\u6570\u5fc5\u987b\u4e0ecallback\u51fd\u6570\u53c2\u6570\u5339\u914d(request\uff0cresponse\u9664\u5916)\n   # url_base\u4e3acallback\u5b9e\u9645\u8fd0\u884c\u7684\u670d\u52a1\u7aefapi\u5730\u5740\uff0ceg: http://127.0.0.1:9000\n   # update_task\u51fd\u6570\u63a5\u53d7data\u548ctask_id\u53c2\u6570\uff0c\u5176\u4e2dtask_id\u5fc5\u987b\u4e3akwargs\u5f62\u5f0f\u4f20\u53c2\n   # async_helper.send_callback(url_base, callback.update_task,\n   #                             data,\n   #                            task_id=task_id)\n   # remote_result \u5bf9\u5e94\u6570\u636e\u4e3aupdate_task\u8fd4\u56de\u7684 res_after\n   remote_result = callback.update_task.remote(result, task_id=task_id)\n   # \u6b64\u5904\u662f\u5f02\u6b65\u56de\u8c03\u7ed3\u679c\uff0c\u4e0d\u9700\u8981\u670d\u52a1\u5668\u7b49\u5f85\u6216\u8005\u8f6e\u8be2\uff0cworker\u4f1a\u4e3b\u52a8\u53d1\u9001\u8fdb\u5ea6\u6216\u8005\u7ed3\u679c\uff0c\u53ef\u4ee5\u4e0dreturn\n   # \u5982\u679c\u60f3\u8981\u4f7f\u7528return\u65b9\u5f0f\uff0c\u5219\u6309\u7167\u6b63\u5e38celery\u6d41\u7a0b\u7f16\u5199\u4ee3\u7801\n   return result\n```\n\ncallback.py\u56de\u8c03\u793a\u4f8b (callback\u4e0d\u5e94\u7406\u89e3\u4e3a\u5f02\u6b65\u4efb\u52a1\u7684\u56de\u8c03\u51fd\u6570\uff0c\u6cdb\u6307talos\u7684\u901a\u7528rpc\u8fdc\u7a0b\u8c03\u7528\uff0c\u53ea\u662f\u76ee\u524d\u6846\u67b6\u5185\u4e3b\u8981\u4f7f\u7528\u65b9\u662f\u5f02\u6b65\u4efb\u52a1)\n```python\nfrom talos.common import async_helper\n# data\u662f\u5f3a\u5236\u53c2\u6570\uff0ctask_id\u4e3aurl\u5f3a\u5236\u53c2\u6570(\u5982\u679curl\u6ca1\u6709\u53c2\u6570\uff0c\u5219\u51fd\u6570\u4e5f\u65e0\u9700task_id)\n# task_id\u4e3aurl\u5f3a\u5236\u53c2\u6570\uff0c\u9ed8\u8ba4\u7c7b\u578b\u662f\u5b57\u7b26\u4e32(\u6bd4\u5982/callback/add/{x}/{y}\uff0c\u51fd\u6570\u5185\u76f4\u63a5\u6267\u884cx+y\u7ed3\u679c\u4f1a\u662f\u5b57\u7b26\u4e32\u62fc\u63a5\uff0c\u56e0\u4e3a\u7531\u4e8e\u6b64\u53c2\u6570\u4eceurl\u4e2d\u63d0\u53d6\uff0c\u6240\u4ee5\u9ed8\u8ba4\u7c7b\u578b\u4e3astr\uff0c\u9700\u8981\u7279\u522b\u6ce8\u610f)\n@async_helper.callback('/callback/add/{task_id}')\ndef update_task(data, task_id):\n    # \u8fdc\u7a0b\u8c03\u7528\u771f\u6b63\u6267\u884c\u65b9\u5728api server\u670d\u52a1\uff0c\u56e0\u6b64\u9ed8\u8ba4\u53ef\u4ee5\u4f7f\u7528\u6570\u636e\u5e93\u64cd\u4f5c\n    res_before,res_after = task_db_api().update(task_id, data)\n    # \u51fd\u6570\u53ef\u8fd4\u56de\u53efjson\u5316\u7684\u6570\u636e\uff0c\u5e76\u8fd4\u56de\u5230\u8c03\u7528\u5ba2\u6237\u7aef\u53bb\n    return res_after\n```\n\nroute\u4e2d\u6ce8\u518c\u56de\u8c03\u51fd\u6570\uff0c\u5426\u5219\u65e0\u6cd5\u627e\u5230\u6b64\u8fdc\u7a0b\u8c03\u7528\n```python\nfrom talos.common import async_helper\nfrom project_name.workers.app_name import callback\n\ndef add_route(api):\n    async_helper.add_callback_route(api, callback.callback_add)\n```\n\n\u542f\u52a8worker\n  celery -A cms.server.celery_worker worker --autoscale=50,4 --loglevel=DEBUG -Q your_queue_name\n\n\u8c03\u7528\n  add.delay('id', 1, 1)\n  \u4f1a\u6709\u4efb\u52a1\u53d1\u9001\u5230worker\u4e2d\uff0c\u7136\u540ewoker\u4f1a\u542f\u52a8\u4e00\u4e2aother_task\u4efb\u52a1\uff0c\u5e76\u56de\u8c03url\u5c06\u7ed3\u679c\u53d1\u9001\u4f1a\u670d\u52a1\u7aef\n\n  (\u5982\u679cAPI\u6a21\u5757\u6709\u7edf\u4e00\u6743\u9650\u6821\u9a8c\uff0c\u8bf7\u6ce8\u610f\u653e\u884c\uff09\n\n\n\n##### \u5f02\u6b65\u4efb\u52a1\u914d\u7f6e\n\n\u4f9d\u8d56\uff1a\n\u200b    \u5e93\uff1a\n\u200b        celery\n\n\u200b    \u914d\u7f6e\uff1a\n\n```\n{\n        ...\n        \"celery\": {\n            \"worker_concurrency\": 8,\n            \"broker_url\": \"pyamqp://guest@127.0.0.1//\",\n            \"result_backend\": \"redis://127.0.0.1\",\n            \"imports\": [\n                \"project_name.workers.app_name.tasks\"\n            ],\n            \"task_serializer\": \"json\",\n            \"result_serializer\": \"json\",\n            \"accept_content\": [\"json\"],\n            \"worker_prefetch_multiplier\": 1,\n            \"task_routes\": {\n                \"project_name.workers.*\": {\"queue\": \"your_queue_name\",\n                                        \"exchange\": \"your_exchange_name\",\n                                        \"routing_key\": \"your_routing_name\"}\n            }\n        },\n        \"worker\": {\n            \"callback\": {\n                \"strict_client\": true,\n                \"allow_hosts\": [\"127.0.0.1\"]\n            }\n        }\n}\n```\n\n\n\n\n\n#### \u5b9a\u65f6\u4efb\u52a1[^ 2]\n\ntalos\u4e2d\u4f60\u53ef\u4ee5\u4f7f\u7528\u539f\u751fcelery\u7684\u5b9a\u65f6\u4efb\u52a1\u673a\u5236\uff0c\u4e5f\u53ef\u4ee5\u4f7f\u7528talos\u4e2d\u63d0\u4f9b\u7684\u6269\u5c55\u5b9a\u65f6\u4efb\u52a1(TScheduler)\uff0c\u6269\u5c55\u7684\u5b9a\u65f6\u4efb\u52a1\u53ef\u4ee5\u57285s(\u53ef\u901a\u8fc7beat_max_loop_interval\u6765\u4fee\u6539\u8fd9\u4e2a\u65f6\u95f4)\u5185\u53d1\u73b0\u5b9a\u65f6\u4efb\u52a1\u7684\u53d8\u5316\u5e76\u5237\u65b0\u8c03\u5ea6\uff0c\u4ece\u800c\u63d0\u4f9b\u52a8\u6001\u7684\u5b9a\u65f6\u4efb\u52a1\uff0c\u800c\u5b9a\u65f6\u4efb\u52a1\u7684\u6765\u6e90\u53ef\u4ee5\u4ece\u914d\u7f6e\u6587\u4ef6\uff0c\u4e5f\u53ef\u4ee5\u901a\u8fc7\u81ea\u5b9a\u4e49\u7684\u51fd\u6570\u4e2d\u52a8\u6001\u63d0\u4f9b\n\n> \u539f\u751fcelery\u7684scheduler\u662f\u4e0d\u652f\u6301\u52a8\u6001\u5b9a\u65f6\u4efb\u52a1\u7684\n\n> \u4f7f\u7528\u539f\u751fcelery\u5b9a\u65f6\u4efb\u52a1\u56e0\u4e3atalos\u914d\u7f6e\u9879\u4e3ajson\u6570\u636e\u800c\u65e0\u6cd5\u63d0\u4f9b\u590d\u6742\u7c7b\u578b\u7684schedule\uff0c\u5f53\u7136\u4e5f\u53ef\u4ee5\u4f7f\u7528add_periodic_task\u6765\u89e3\u51b3\uff0c\u4f46\u4f1a\u964d\u4f4e\u6211\u4eec\u4f7f\u7528\u7684\u4fbf\u5229\u6027\n>\n> \u8fd9\u4e9b\u95ee\u9898\u5728talos\u6269\u5c55\u5b9a\u65f6\u4efb\u52a1\u4e2d\u5f97\u4ee5\u89e3\u51b3\n\n##### \u9759\u6001\u914d\u7f6e\u5b9a\u65f6\u4efb\u52a1\uff1a\n\n\u4f7f\u7528\u6700\u539f\u59cb\u7684celery\u5b9a\u65f6\u4efb\u52a1\u914d\u7f6e\uff0c\u6700\u5feb\u6377\u7684\u5b9a\u65f6\u4efb\u52a1\u4f8b\u5b50[^ 3]\uff1a\n\n```json\n    \"celery\": {\n        \"worker_concurrency\": 8,\n        \"broker_url\": \"pyamqp://test:test@127.0.0.1//\",\n        ...\n        \"beat_schedule\": {\n            \"test_every_5s\": {\n                \"task\": \"cms.workers.periodic.tasks.test_add\",\n                \"schedule\": 5,\n                \"args\": [3,6] \n            }\n        }\n```\n\n\u542f\u52a8beat\uff1a celery -A cms.server.celery_worker beat --loglevel=DEBUG\n\n\u542f\u52a8worker\uff1acelery -A cms.server.celery_worker worker --loglevel=DEBUG -Q cms-dev-queue\n\n\u53ef\u4ee5\u770b\u5230\u6bcf5s\uff0cbeat\u4f1a\u53d1\u9001\u4e00\u4e2a\u4efb\u52a1\uff0cworker\u4f1a\u63a5\u6536\u6b64\u4efb\u52a1\u8fdb\u884c\u5904\u7406\uff0c\u4ece\u800c\u5f62\u6210\u5b9a\u65f6\u4efb\u52a1\n\n\u4f7f\u7528\u8fc7\u539f\u751fcelery\u7684\u4eba\u53ef\u80fd\u770b\u51fa\u8fd9\u91cc\u5b58\u5728\u7684\u95ee\u9898\uff1acrontab\u662f\u5bf9\u8c61\uff0cjson\u914d\u7f6e\u662f\u65e0\u6cd5\u4f20\u9012\uff0c\u53ea\u80fd\u914d\u7f6e\u7b80\u5355\u7684\u95f4\u9694\u4efb\u52a1\uff0c\u786e\u5b9e\uff0c\u7f3a\u7701\u60c5\u51b5\u4e0b\u7531\u4e8e\u914d\u7f6e\u6587\u4ef6\u683c\u5f0f\u7684\u539f\u56e0\u65e0\u6cd5\u63d0\u4f9b\u66f4\u9ad8\u7ea7\u7684\u5b9a\u65f6\u4efb\u52a1\u914d\u7f6e\uff0c\u6240\u4ee5talos\u63d0\u4f9b\u4e86\u81ea\u5b9a\u4e49\u7684Scheduler\uff1aTScheduler\uff0c\u8fd9\u4e2a\u8c03\u5ea6\u5668\u53ef\u4ee5\u4ece\u914d\u7f6e\u6587\u4ef6\u4e2d\u89e3\u6790interval\u3001crontab\u7c7b\u578b\u7684\u5b9a\u65f6\u4efb\u52a1\uff0c\u4ece\u800c\u8986\u76d6\u66f4\u5e7f\u6cdb\u7684\u9700\u6c42\uff0c\u800c\u4f7f\u7528\u4e5f\u975e\u5e38\u7b80\u5355\uff1a\n\n```json\n\"celery\": {\n    \"worker_concurrency\": 8,\n    \"broker_url\": \"pyamqp://test:test@127.0.0.1//\",\n    ...\n    \"beat_schedule\": {\n        \"test_every_5s\": {\n            \"task\": \"cms.workers.periodic.tasks.test_add\",\n            \"schedule\": 5,\n            \"args\": [3,6] \n        },\n        \"test_every_123s\": {\n            \"type\": \"interval\",\n            \"task\": \"cms.workers.periodic.tasks.test_add\",\n            \"schedule\": \"12.3\",\n            \"args\": [3,6] \n        },\n        \"test_crontab_simple\": {\n            \"type\": \"crontab\",\n            \"task\": \"cms.workers.periodic.tasks.test_add\",\n            \"schedule\": \"*/1\",\n            \"args\": [3,6] \n        },\n        \"test_crontab\": {\n            \"type\": \"crontab\",\n            \"task\": \"cms.workers.periodic.tasks.test_add\",\n            \"schedule\": \"1,13,30-45,50-59/2 *1 * * *\",\n            \"args\": [3,6] \n        }\n    }\n```\n\u4f9d\u7136\u662f\u5728\u914d\u7f6e\u6587\u4ef6\u4e2d\u5b9a\u4e49\uff0c\u591a\u4e86\u4e00\u4e2atype\u53c2\u6570\uff0c\u7528\u4e8e\u5e2e\u52a9\u8c03\u5ea6\u5668\u89e3\u6790\u5b9a\u65f6\u4efb\u52a1\uff0c\u6b64\u5916\u8fd8\u9700\u8981\u6307\u5b9a\u4f7f\u7528talos\u7684TScheduler\u8c03\u5ea6\u5668\uff0c\u6bd4\u5982\u914d\u7f6e\u4e2d\u6307\u5b9a:\n\n```\n\"celery\": {\n    \"worker_concurrency\": 8,\n    \"broker_url\": \"pyamqp://test:test@127.0.0.1//\",\n    ...\n    \"beat_schedule\": {...}\n    \"beat_scheduler\": \"talos.common.scheduler:TScheduler\"\n```\n\n\u6216\u8005\u547d\u4ee4\u884c\u542f\u52a8\u65f6\u6307\u5b9a\uff1a\n\n\u542f\u52a8beat\uff1a celery -A cms.server.celery_worker beat --loglevel=DEBUG -S talos.common.scheduler:TScheduler \n\n\u542f\u52a8worker\uff1acelery -A cms.server.celery_worker worker --loglevel=DEBUG -Q cms-dev-queue\n\n\u9664\u4e86type\uff0cTScheduler\u7684\u4efb\u52a1\u8fd8\u63d0\u4f9b\u4e86\u5f88\u591a\u5176\u4ed6\u7684\u6269\u5c55\u5c5e\u6027\uff0c\u4ee5\u4e0b\u662f\u5c5e\u6027\u4ee5\u53ca\u5176\u63cf\u8ff0\n\n```\nname:           string, \u552f\u4e00\u540d\u79f0\ntask:           string, \u4efb\u52a1\u6a21\u5757\u51fd\u6570\n[description]:  string, \u5907\u6ce8\u4fe1\u606f\n[type]:         string, interval \u6216 crontab, \u9ed8\u8ba4 interval\nschedule:       string/int/float/schedule eg. 1.0,'5.1', '10 *' , '*/10 * * * *' \nargs:           tuple/list, \u53c2\u6570\nkwargs:         dict, \u547d\u540d\u53c2\u6570\n[priority]:     int, \u4f18\u5148\u7ea7, \u9ed8\u8ba45\n[expires]:      int, \u5355\u4f4d\u4e3a\u79d2\uff0c\u5f53\u4efb\u52a1\u4ea7\u751f\u540e\uff0c\u591a\u4e45\u8fd8\u6ca1\u88ab\u6267\u884c\u4f1a\u8ba4\u4e3a\u8d85\u65f6\n[enabled]:      bool, True/False, \u9ed8\u8ba4True\n[max_calls]:    None/int, \u6700\u5927\u8c03\u5ea6\u6b21\u6570, \u9ed8\u8ba4None\u65e0\u9650\u5236\n[last_updated]: Datetime, \u4efb\u52a1\u6700\u540e\u66f4\u65b0\u65f6\u95f4\uff0c\u5e38\u7528\u4e8e\u5224\u65ad\u662f\u5426\u6709\u5b9a\u65f6\u4efb\u52a1\u9700\u8981\u66f4\u65b0\n```\n\n\n\n##### \u52a8\u6001\u914d\u7f6e\u5b9a\u65f6\u4efb\u52a1\uff1a\n\nTScheduler\u7684\u52a8\u6001\u4efb\u52a1\u4ec5\u9650\u7528\u6237\u81ea\u5b9a\u4e49\u7684\u6240\u6709schedules\n\u6240\u6709\u5b9a\u65f6\u4efb\u52a1 = \u914d\u7f6e\u6587\u4ef6\u4efb\u52a1 + add_periodic_task\u4efb\u52a1 + hooks\u4efb\u52a1\uff0chooks\u4efb\u52a1\u53ef\u4ee5\u901a\u8fc7\u76f8\u540cname\u6765\u8986\u76d6\u5df2\u5b58\u5728\u914d\u7f6e\u4e2d\u7684\u4efb\u52a1\uff0c\u5426\u5219\u76f8\u4e92\u72ec\u7acb\n\n- \u4f7f\u7528TScheduler\u9884\u7559\u7684hooks\u8fdb\u884c\u52a8\u6001\u5b9a\u65f6\u4efb\u52a1\u914d\u7f6e(\u63a8\u8350\u65b9\u5f0f)\uff1a\n\n  TScheduler\u4e2d\u9884\u7559\u4e862\u4e2ahooks\uff1atalos_on_user_schedules_changed/talos_on_user_schedules\n\n  **talos_on_user_schedules_changed**\u94a9\u5b50\u7528\u4e8e\u5224\u65ad\u662f\u5426\u9700\u8981\u66f4\u65b0\u5b9a\u65f6\u5668\uff0c\u94a9\u5b50\u88ab\u6267\u884c\u7684\u6700\u5c0f\u95f4\u9694\u662fbeat_max_loop_interval(\u5982\u4e0d\u8bbe\u7f6e\u9ed8\u8ba4\u4e3a5s)\n\n  \u94a9\u5b50\u5b9a\u4e49\u4e3acallable(scheduler)\uff0c\u8fd4\u56de\u503c\u662fTrue/False\n\n  **talos_on_user_schedules**\u94a9\u5b50\u7528\u4e8e\u63d0\u4f9b\u65b0\u7684\u5b9a\u65f6\u5668\u5b57\u5178\u6570\u636e\n\n  \u94a9\u5b50\u5b9a\u4e49\u4e3acallable(scheduler)\uff0c\u8fd4\u56de\u503c\u662f\u5b57\u5178\uff0c\u5168\u91cf\u7684\u81ea\u5b9a\u4e49\u52a8\u6001\u5b9a\u65f6\u5668\n\n  \u6211\u4eec\u6765\u5c1d\u8bd5\u63d0\u4f9b\u4e00\u4e2a\uff0c\u6bcf\u8fc713\u79d2\u81ea\u52a8\u751f\u6210\u4e00\u4e2a\u5168\u65b0\u5b9a\u65f6\u5668\u7684\u4ee3\u7801\n\n  \u4ee5\u4e0b\u662fcms.workers.periodic.hooks.py\u7684\u6587\u4ef6\u5185\u5bb9\n\n  ```python\n  import datetime\n  from datetime import timedelta\n  import random\n  \n  # talos_on_user_schedules_changed, \u7528\u4e8e\u5224\u65ad\u662f\u5426\u9700\u8981\u66f4\u65b0\u5b9a\u65f6\u5668\n  # \u9ed8\u8ba4\u6bcf5s\u8c03\u7528\u4e00\u6b21\n  class ChangeDetection(object):\n      '''\n      \u7b49\u4ef7\u4e8e\u51fd\u6570\uff0c\u53ea\u662f\u6b64\u5904\u6211\u4eec\u9700\u8981\u4fdd\u7559_last_modify\u5c5e\u6027\u6240\u4ee5\u7528\u7c7b\u6765\u5b9a\u4e49callable\n      def ChangeDetection(scheduler):\n          ...do something...\n      '''\n      def __init__(self, scheduler):\n          self._last_modify = self.now()\n      def now(self):\n          return datetime.datetime.now()\n      def __call__(self, scheduler):\n          now = self.now()\n          # \u6bcf\u8fc713\u79d2\u5b9a\u4e49\u5b9a\u65f6\u5668\u6709\u66f4\u65b0\n          if now - self._last_modify >= timedelta(seconds=13):\n              self._last_modify = now\n              return True\n          return False\n  \n  # talos_on_user_schedules, \u7528\u4e8e\u63d0\u4f9b\u65b0\u7684\u5b9a\u65f6\u5668\u5b57\u5178\u6570\u636e\n  # \u5728talos_on_user_schedules_changed hooks\u8fd4\u56deTrue\u540e\u88ab\u8c03\u7528\n  class Schedules(object):\n      '''\n      \u7b49\u4ef7\u4e8e\u51fd\u6570\n      def Schedules(scheduler):\n          ...do something...\n      '''\n      def __init__(self, scheduler):\n          pass\n      def __call__(self, scheduler):\n          interval = random.randint(1,10)\n          name = 'dynamic_every_%s s' % interval\n          # \u751f\u6210\u4e00\u4e2a\u7eaf\u968f\u673a\u7684\u5b9a\u65f6\u4efb\u52a1\n          return {name: {'task': 'cms.workers.periodic.tasks.test_add', 'schedule': interval, 'args': (1,3)}}\n  ```\n\n  \u914d\u7f6e\u6587\u4ef6\u5982\u4e0b\uff1a\n\n  ```json\n      \"celery\": {\n          ...\n          \"beat_schedule\": {\n              \"every_5s_max_call_2_times\": {\n                  \"task\": \"cms.workers.periodic.tasks.test_add\",\n                  \"schedule\": \"5\",\n                  \"max_calls\": 2,\n                  \"enabled\": true,\n                  \"args\": [1, 3]\n              }\n          },\n          \"talos_on_user_schedules_changed\":[\n              \"cms.workers.periodic.hooks:ChangeDetection\"],\n          \"talos_on_user_schedules\": [\n              \"cms.workers.periodic.hooks:Schedules\"]\n      },\n  ```\n\n  \u5f97\u5230\u7684\u7ed3\u679c\u662f\uff0c\u4e00\u4e2a\u6bcf5s\uff0c\u6700\u591a\u8c03\u5ea62\u6b21\u7684\u5b9a\u65f6\u4efb\u52a1\uff1b\u4e00\u4e2a\u6bcf>=13s\u81ea\u52a8\u751f\u6210\u7684\u968f\u673a\u5b9a\u65f6\u4efb\u52a1\n\n- \u4f7f\u7528\u5b98\u65b9\u7684setup_periodic_tasks\u8fdb\u884c\u52a8\u6001\u914d\u7f6e\n\n  \u89c1celery\u6587\u6863\n\n  \u622a\u6b622018.11.13 celery 4.2.0\u5728\u5b9a\u65f6\u4efb\u52a1\u4e2d\u4f9d\u7136\u5b58\u5728\u95ee\u9898\uff0c\u4f7f\u7528\u5b98\u65b9\u5efa\u8bae\u7684on_after_configure\u52a8\u6001\u914d\u7f6e\u5b9a\u65f6\u5668\u65f6\uff0c\u5b9a\u65f6\u4efb\u52a1\u4e0d\u4f1a\u88ab\u89e6\u53d1\uff1a[GitHub Issue 3589](https://github.com/celery/celery/issues/3589)\n\n  ```\n  @celery.app.on_after_configure.connect\n  def setup_periodic_tasks(sender, **kwargs):\n      sender.add_periodic_task(3.0, test.s('add every 3s by add_periodic_task'), name='add every 3s by add_periodic_task')\n  \n  @celery.app.task\n  def test(arg):\n      print(arg)\n  ```\n\n\u800c\u6d4b\u8bd5\u4ee5\u4e0b\u4ee3\u7801\u6709\u6548\uff0c\u53ef\u4ee5\u4f7f\u7528\u4ee5\u4e0b\u65b9\u6cd5\uff1a\n\n```\n@celery.app.on_after_finalize.connect\ndef setup_periodic_tasks(sender, **kwargs):\n    sender.add_periodic_task(3.0, test.s('add every 3s by add_periodic_task'), name='add every 3s by add_periodic_task')\n\n@celery.app.task\ndef test(arg):\n    print(arg)\n```\n\n#### \u9891\u7387\u9650\u5236\n\n##### controller & \u4e2d\u95f4\u4ef6 \u9891\u7387\u9650\u5236\n\n\u4e3b\u8981\u7528\u4e8ehttp\u63a5\u53e3\u9891\u7387\u9650\u5236\n\n    \u57fa\u672c\u4f7f\u7528\u6b65\u9aa4\uff1a\n    \n    - \u5728controller\u4e0a\u914d\u7f6e\u88c5\u9970\u5668\n    - \u5c06Limiter\u914d\u7f6e\u5230\u542f\u52a8\u4e2d\u95f4\u4ef6\n    \n    \u88c5\u9970\u5668\u901a\u8fc7\u7ba1\u7406\u6620\u5c04\u5173\u7cfb\u8868LIMITEDS\uff0cLIMITEDS_EXEMPT\u6765\u5b9a\u4f4d\u7528\u6237\u8bbe\u7f6e\u7684\u7c7b\u5b9e\u4f8b->\u9891\u7387\u9650\u5236\u5668\u5173\u7cfb\uff0c\n    \u9891\u7387\u9650\u5236\u5668\u662f\u5b9e\u4f8b\u7ea7\u522b\u7684\uff0c\u610f\u5473\u7740\u6bcf\u4e2a\u5b9e\u4f8b\u90fd\u4f7f\u7528\u81ea\u5df1\u7684\u9891\u7387\u9650\u5236\u5668\n    \n    \u9891\u7387\u9650\u5236\u5668\u67097\u4e2a\u4e3b\u8981\u53c2\u6570\uff1a\u9891\u7387\u8bbe\u7f6e\uff0c\u5173\u952e\u9650\u5236\u53c2\u6570\uff0c\u9650\u5236\u8303\u56f4\uff0c\u662f\u5426\u5bf9\u72ec\u7acb\u65b9\u6cd5\u8fdb\u884c\u4e0d\u540c\u9650\u5236, \u7b97\u6cd5\uff0c\u9519\u8bef\u63d0\u793a\u4fe1\u606f, hit\u51fd\u6570\n    \n    :param limit_value: \u9891\u7387\u8bbe\u7f6e\uff1a\u683c\u5f0f[count] [per|/] [n (optional)][second|minute|hour|day|month|year]\n    :param key_function: \u5173\u952e\u9650\u5236\u53c2\u6570\uff1a\u9ed8\u8ba4\u4e3aIP\u5730\u5740(\u652f\u6301X-Forwarded-For)\uff0c\u81ea\u5b9a\u4e49\u51fd\u6570\uff1adef key_func(req) -> string\n    :param scope: \u9650\u5236\u8303\u56f4\u7a7a\u95f4\uff1a\u9ed8\u8ba4python\u7c7b\u5b8c\u6574\u8def\u5f84\uff0c\u81ea\u5b9a\u4e49\u51fd\u6570def scope_func(request) -> string\n    :param per_method: \u6307\u5b9a\u662f\u5426\u6839\u636e\u6bcf\u4e2aHTTP\u65b9\u6cd5\u533a\u5206\u9891\u7387\u9650\u5236\uff0c\u9ed8\u8ba4True\n    :param strategy: \u7b97\u6cd5\uff1a\u652f\u6301fixed-window\u3001fixed-window-elastic-expiry\u3001moving-window\n    :param message: \u9519\u8bef\u63d0\u793a\u4fe1\u606f\uff1a\u9519\u8bef\u63d0\u793a\u4fe1\u606f\u53ef\u63a5\u53d73\u4e2a\u683c\u5f0f\u5316\uff08limit\uff0cremaining\uff0creset\uff09\u5185\u5bb9\n    :param hit_func: \u51fd\u6570\u5b9a\u4e49\u4e3adef hit(controller, request) -> bool\uff0c\u4e3aTrue\u65f6\u5219\u89e6\u53d1\u9891\u7387\u9650\u5236\u5668hit\uff0c\u5426\u5219\u5ffd\u7565\n\n> PS\uff1a\u771f\u6b63\u7684\u9891\u7387\u9650\u5236\u8303\u56f4 = \u5173\u952e\u9650\u5236\u53c2\u6570(\u9ed8\u8ba4IP\u5730\u5740) + \u9650\u5236\u8303\u56f4(\u9ed8\u8ba4python\u7c7b\u5b8c\u6574\u8def\u5f84) + \u65b9\u6cd5\u540d(\u5982\u679c\u533a\u5206\u72ec\u7acb\u65b9\u6cd5)\uff0c\u5f53\u6b64\u9891\u7387\u8303\u56f4\u88ab\u547d\u4e2d\u540e\u624d\u4f1a\u89e6\u53d1\u9891\u7387\u9650\u5236\n\n\n\n\n\n###### \u9759\u6001\u9891\u7387\u9650\u5236(\u914d\u7f6e/\u4ee3\u7801)\n\n**controller\u7ea7\u7684\u9891\u7387\u9650\u5236**\n\n```python\n# coding=utf-8\n\nimport falcon\nfrom talos.common import decorators as deco\nfrom talos.common import limitwrapper\n\n# \u5feb\u901f\u81ea\u5b9a\u4e49\u4e00\u4e2a\u7b80\u5355\u652f\u6301GET\u3001POST\u8bf7\u6c42\u7684Controller\n# add_route('/things', ThingsController())\n\n@deco.limit('1/second')\nclass ThingsController(object):\n    def on_get(self, req, resp):\n        \"\"\"Handles GET requests, using 1/second limit\"\"\"\n        resp.body = ('It works!')\n    def on_post(self, req, resp):\n        \"\"\"Handles POST requests, using global limit(if any)\"\"\"\n        resp.body = ('It works!')\n```\n\n###### \u5168\u5c40\u7ea7\u7684\u9891\u7387\u9650\u5236\n\n```json\n{\n    \"rate_limit\": {\n        \"enabled\": true,\n        \"storage_url\": \"memory://\",\n        \"strategy\": \"fixed-window\",\n        \"global_limits\": \"5/second\",\n        \"per_method\": true,\n        \"header_reset\": \"X-RateLimit-Reset\",\n        \"header_remaining\": \"X-RateLimit-Remaining\",\n        \"header_limit\": \"X-RateLimit-Limit\"\n    }\n}\n```\n\n###### \u57fa\u4e8e\u4e2d\u95f4\u4ef6\u52a8\u6001\u9891\u7387\u9650\u5236\n\n\u4ee5\u4e0a\u7684\u9891\u7387\u9650\u5236\u90fd\u662f\u9884\u5b9a\u4e49\u7684\uff0c\u65e0\u6cd5\u6839\u636e\u5177\u4f53\u53c2\u6570\u8fdb\u884c\u52a8\u6001\u7684\u66f4\u6539\uff0c\u800c\u901a\u8fc7\u91cd\u5199\u4e2d\u95f4\u4ef6\u7684get_extra_limits\u51fd\u6570\uff0c\u6211\u4eec\u53ef\u4ee5\u83b7\u5f97\u52a8\u6001\u8ffd\u52a0\u9891\u7387\u9650\u5236\u7684\u80fd\u529b\n\n```python\nclass MyLimiter(limiter.Limiter):\n    def __init__(self, *args, **kwargs):\n        super(MyLimiter, self).__init__(*args, **kwargs)\n        self.mylimits = {'cms.apps.test1': [wrapper.LimitWrapper('2/second')]}\n    def get_extra_limits(self, request, resource, params):\n        if request.method.lower() == 'post':\n            return self.mylimits['cms.apps.test1']\n\n```\n\n\u9891\u7387\u9650\u5236\u9ed8\u8ba4\u88ab\u52a0\u8f7d\u5728\u4e86\u7cfb\u7edf\u7684\u4e2d\u95f4\u4ef6\u4e2d\uff0c\u5982\u679c\u4e0d\u5e0c\u671b\u91cd\u590d\u5b9a\u4e49\u4e2d\u95f4\u4ef6\uff0c\u53ef\u4ee5\u5728cms.server.wsgi_server\u4e2d\u4fee\u6539\u9879\u76ee\u6e90\u4ee3\u7801\uff1a\n\n```python\napplication = base.initialize_server('cms',\n                                     ...\n                                     middlewares=[\n                                         globalvars.GlobalVars(),\n                                         MyLimiter(),\n                                         json_translator.JSONTranslator()],\n                                     override_middlewares=True)\n```\n\n##### \u51fd\u6570\u7ea7\u9891\u7387\u9650\u5236\n\n```python\nfrom talos.common import decorators as deco\n\n@deco.flimit('1/second')\ndef test():\n    pass\n```\n\n\n\n    \u7528\u4e8e\u88c5\u9970\u4e00\u4e2a\u51fd\u6570\u8868\u793a\u5176\u53d7\u9650\u4e8e\u6b64\u8c03\u7528\u9891\u7387\n    \u5f53\u88c5\u9970\u7c7b\u6210\u5458\u51fd\u6570\u65f6\uff0c\u9891\u7387\u9650\u5236\u8303\u56f4\u662f\u7c7b\u7ea7\u522b\u7684\uff0c\u610f\u5473\u7740\u7c7b\u7684\u4e0d\u540c\u5b9e\u4f8b\u5171\u4eab\u76f8\u540c\u7684\u9891\u7387\u9650\u5236\uff0c\n    \u5982\u679c\u9700\u8981\u5b9e\u4f8b\u7ea7\u9694\u79bb\u7684\u9891\u7387\u9650\u5236\uff0c\u9700\u8981\u624b\u52a8\u6307\u5b9akey_func\uff0c\u5e76\u4f7f\u7528\u8fd4\u56de\u5b9e\u4f8b\u6807\u8bc6\u4f5c\u4e3a\u9650\u5236\u53c2\u6570\n    \n    :param limit_value: \u9891\u7387\u8bbe\u7f6e\uff1a\u683c\u5f0f[count] [per|/] [n (optional)][second|minute|hour|day|month|year]\n    :param scope: \u9650\u5236\u8303\u56f4\u7a7a\u95f4\uff1a\u9ed8\u8ba4python\u7c7b/\u51fd\u6570\u5b8c\u6574\u8def\u5f84 or \u81ea\u5b9a\u4e49\u5b57\u7b26\u4e32.\n    :param key_func: \u5173\u952e\u9650\u5236\u53c2\u6570\uff1a\u9ed8\u8ba4\u4e3a\u7a7a\u5b57\u7b26\u4e32\uff0c\u81ea\u5b9a\u4e49\u51fd\u6570\uff1adef key_func(*args, **kwargs) -> string\n    :param strategy: \u7b97\u6cd5\uff1a\u652f\u6301fixed-window\u3001fixed-window-elastic-expiry\u3001moving-window\n    :param message: \u9519\u8bef\u63d0\u793a\u4fe1\u606f\uff1a\u9519\u8bef\u63d0\u793a\u4fe1\u606f\u53ef\u63a5\u53d73\u4e2a\u683c\u5f0f\u5316\uff08limit\uff0cremaining\uff0creset\uff09\u5185\u5bb9\n    :param storage: \u9891\u7387\u9650\u5236\u540e\u7aef\u5b58\u50a8\u6570\u636e\uff0c\u5982: memory://, redis://:pass@localhost:6379\n    :param hit_func: \u51fd\u6570\u5b9a\u4e49\u4e3adef hit(result) -> bool\uff08\u53c2\u6570\u4e3a\u7528\u6237\u51fd\u6570\u6267\u884c\u7ed3\u679c\uff0c\u82e5delay_hit=False\uff0c\u5219\u53c2\u6570\u4e3aNone\uff09\uff0c\u4e3aTrue\u65f6\u5219\u89e6\u53d1\u9891\u7387\u9650\u5236\u5668hit\uff0c\u5426\u5219\u5ffd\u7565\n    :param delay_hit: \u9ed8\u8ba4\u5728\u51fd\u6570\u6267\u884c\u524d\u6d4b\u8bd5\u9891\u7387hit(False)\uff0c\u53ef\u4ee5\u8bbe\u7f6e\u4e3aTrue\u5c06\u9891\u7387\u6d4b\u8bd5hit\u653e\u7f6e\u5728\u51fd\u6570\u6267\u884c\u540e\uff0c\u642d\u914dhit_func\n                       \u4f7f\u7528\uff0c\u53ef\u4ee5\u83b7\u53d6\u5230\u51fd\u6570\u6267\u884c\u7ed3\u679c\u6765\u63a7\u5236\u662f\u5426\u6267\u884chit\n\u5173\u4e8e\u51fd\u6570\u9891\u7387\u9650\u5236\u6a21\u5757\u66f4\u591a\u7528\u4f8b\uff0c\u8bf7\u89c1\u5355\u5143\u6d4b\u8bd5tests.test_limit_func\n\n#### \u6570\u636e\u5e93\u7248\u672c\u7ba1\u7406\n\n\u4fee\u6539models.py\u4e3a\u6700\u7ec8\u76ee\u6807\u8868\u6a21\u578b\uff0c\u8fd0\u884c\u547d\u4ee4\uff1a\n\nalembic revision --autogenerate -m \"add table: xxxxx\"\n\n\u5907\u6ce8\u4e0d\u652f\u6301\u4e2d\u6587, autogenerate\u7528\u4e8e\u751f\u6210upgrade\uff0cdowngrade\u51fd\u6570\u5185\u5bb9\uff0c\u751f\u6210\u540e\u9700\u68c0\u67e5\u5347\u7ea7\u964d\u7ea7\u51fd\u6570\u662f\u5426\u6b63\u786e\n\n\u5347\u7ea7\uff1aalembic upgrade head\n\n\u964d\u7ea7\uff1aalembic downgrade base\n\nhead\u6307\u6700\u65b0\u7248\u672c\uff0cbase\u6307\u6700\u539f\u59cb\u7248\u672c\u5373models\u7b2c\u4e00\u4e2aversion\uff0c\u66f4\u591a\u5347\u7ea7\u964d\u7ea7\u65b9\u5f0f\u5982\u4e0b\uff1a\n\n- alembic upgrade +2 \u5347\u7ea72\u4e2a\u7248\u672c\n\n- alembic downgrade -1 \u56de\u9000\u4e00\u4e2a\u7248\u672c\n\n- alembic upgrade ae10+2 \u5347\u7ea7\u5230ae1027a6acf+2\u4e2a\u7248\u672c\n\n```python\n# alembic \u811a\u672c\u5185\u624b\u52a8\u6267\u884csql\u8bed\u53e5\nop.execute('raw sql ...')\n```\n\n\n\n\n#### \u5355\u5143\u6d4b\u8bd5\n\ntalos\u751f\u6210\u7684\u9879\u76ee\u9884\u7f6e\u4e86\u4e00\u4e9b\u4f9d\u8d56\u8981\u6c42\uff0c\u53ef\u4ee5\u66f4\u4fbf\u6377\u7684\u4f7f\u7528pytest\u8fdb\u884c\u5355\u5143\u6d4b\u8bd5\uff0c\u5982\u9700\u4e86\u89e3\u66f4\u8be6\u7ec6\u7684\u5355\u5143\u6d4b\u8bd5\u7f16\u5199\u6307\u5bfc\uff0c\u8bf7\u67e5\u770bpytest\u6587\u6863\n\n> python setup.py test\n\n\u53ef\u4ee5\u7b80\u5355\u4ece\u547d\u4ee4\u884c\u8f93\u51fa\u4e2d\u67e5\u770b\u7ed3\u679c\uff0c\u6216\u8005\u4eceunit_test_report.html\u67e5\u770b\u5355\u5143\u6d4b\u8bd5\u62a5\u544a\uff0c\u4ecehtmlcov/index.html\u4e2d\u67e5\u770b\u8986\u76d6\u6d4b\u8bd5\u62a5\u544a\u7ed3\u679c\n\n\u793a\u4f8b\u53ef\u4ee5\u4ecetalos\u6e90\u7801\u7684tests\u6587\u4ef6\u5939\u4e2d\u67e5\u770b\n\n```bash\n$ tree tests\ntests\n\u251c\u2500\u2500 __init__.py\n\u251c\u2500\u2500 models.py\n\u251c\u2500\u2500 test_db_filters.py\n\u251c\u2500\u2500 unittest.conf\n\u251c\u2500\u2500 unittest.sqlite3\n\u2514\u2500\u2500 ...\n\n```\n\n\u5355\u5143\u6d4b\u8bd5\u6587\u4ef6\u4ee5test_xxxxxx.py\u4f5c\u4e3a\u547d\u540d\n\n## Sphinx\u6ce8\u91ca\u6587\u6863\n\nSphinx\u7684\u6ce8\u91ca\u683c\u5f0f\u8fd9\u91cc\u4e0d\u518d\u8d58\u8ff0\uff0c\u53ef\u4ee5\u53c2\u8003\u7f51\u4e0a\u6587\u6863\u6559\u7a0b\uff0ctalos\u5185\u90e8\u4f7f\u7528\u7684\u6ce8\u91ca\u6587\u6863\u683c\u5f0f\u5982\u4e0b\uff1a\n\n```\n    \"\"\"\n    \u51fd\u6570\u6ce8\u91ca\u6587\u6863\n\n    :param value: \u53c2\u6570\u63cf\u8ff0\n    :type value: \u53c2\u6570\u7c7b\u578b\n    :returns: \u8fd4\u56de\u503c\u63cf\u8ff0\n    :rtype: `bytes`/`str` \u8fd4\u56de\u503c\u7c7b\u578b\n    \"\"\"\n```\n\n\n\n- \u5b89\u88c5sphinx\n\n- \u5728\u5de5\u7a0b\u76ee\u5f55\u4e0b\u8fd0\u884c\uff1a\n\n  sphinx-quickstart docs\n\n  - root path for the documentation [.]: docs\n  - Project name: cms\n  - Author name(s): Roy\n  - Project version []: 1.0.0\n  - Project language [en]: zh_cn\n  - autodoc: automatically insert docstrings from modules (y/n) [n]: y\n\n- \u53ef\u9009\u7684\u98ce\u683c\u4e3b\u9898\uff0c\u63a8\u8350sphinx_rtd_theme\uff0c\u9700\u8981pip install sphinx_rtd_theme\n\n- \u4fee\u6539docs/conf.py\n\n  ```python\n  # import os\n  # import sys\n  # sys.path.insert(0, os.path.abspath('.'))\n  import os\n  import sys\n  sys.path.insert(0, os.path.abspath('..'))\n  \n  import sphinx_rtd_theme\n  html_theme = \"sphinx_rtd_theme\"\n  html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n  ```\n\n- \u751f\u6210apidoc sphinx-apidoc -o docs/ ./cms\n\n- \u751f\u6210html\uff1a\n\n  - cd docs\n  - make.bat html\n  - \u6253\u5f00docs/_build/html/index.html\n\n## \u56fd\u9645\u5316i18n\n\n\u540c\u6837\u4ee5cms\u9879\u76ee\u4f5c\u4e3a\u4f8b\u5b50\n\n### \u63d0\u53d6\u5f85\u7ffb\u8bd1\n\n```bash\n# \u9700\u8981\u7ffb\u8bd1\u9879\u76ee\u7684\u8bed\u8a00\nfind /usr/lib/python2.7/site-packages/cms/ -name \"*.py\" >POTFILES.in\n# \u9700\u8981\u7ffb\u8bd1talos\u7684\u8bed\u8a00\nfind /usr/lib/python2.7/site-packages/talos/ -name \"*.py\" >>POTFILES.in\n# \u63d0\u53d6\u4e3acms.po\nxgettext --default-domain=cms --add-comments --keyword=_ --keyword=N_ --files-from=POTFILES.in --from-code=UTF8\n```\n\n\n\n### \u5408\u5e76\u5df2\u7ffb\u8bd1\n\n```bash\nmsgmerge cms-old.po cms.po -o cms.po\n```\n\n\n\n### \u7ffb\u8bd1\n\n\u53ef\u4ee5\u4f7f\u7528\u5982Poedit\u7684\u5de5\u5177\u5e2e\u52a9\u7ffb\u8bd1\n\n(\u7565)\n\n### \u7f16\u8bd1\u53d1\u5e03\n\nWindows\uff1a\u4f7f\u7528Poedit\u5de5\u5177\uff0c\u5219\u70b9\u51fb\u4fdd\u5b58\u5373\u53ef\u751f\u6210cms.mo\u6587\u4ef6\n\nLinux\uff1amsgfmt --output-file=cms.mo cms.po\n\n\u5c06mo\u6587\u4ef6\u53d1\u5e03\u5230\n\n/etc/{\\$your_project}/locale/{\\$lang}/LC_MESSAGES/\n\n{\\$lang}\u5373\u914d\u7f6e\u9879\u4e2d\u7684language\n\n\n\n## \u65e5\u5fd7\u914d\u7f6e\n\n### \u914d\u7f6e\u6307\u5f15\n\n\u5168\u5c40\u65e5\u5fd7\u914d\u7f6e\u4e3alog\u5bf9\u8c61\uff0c\u9ed8\u8ba4\u4f7f\u7528WatchedFileHandler\u8fdb\u884c\u65e5\u5fd7\u5904\u7406\uff0c\u800c\u6587\u4ef6\u5219\u4f7f\u7528path\u914d\u7f6e\uff0c\u5982\u679c\u5e0c\u671b\u5168\u5c40\u65e5\u5fd7\u4e2d\u4f7f\u7528\u81ea\u5b9a\u4e49\u7684Handler\uff0c\u5219path\u53c2\u6570\u662f\u53ef\u9009\u7684\n\n\u5168\u5c40\u65e5\u5fd7\u901a\u5e38\u53ef\u4ee5\u89e3\u51b3\u5927\u90e8\u5206\u573a\u666f\uff0c\u4f46\u6709\u65f6\u5019\uff0c\u6211\u4eec\u5e0c\u671b\u4e0d\u540c\u6a21\u5757\u65e5\u5fd7\u8f93\u51fa\u5230\u4e0d\u540c\u6587\u4ef6\u4e2d\uff0c\u53ef\u4ee5\u4f7f\u7528\uff1aloggers\uff0c\u5b50\u65e5\u5fd7\u914d\u7f6e\u5668\uff0c\u5176\u53c2\u6570\u53ef\u5b8c\u5168\u53c2\u8003log\u5168\u5c40\u65e5\u5fd7\u53c2\u6570\uff08\u9664gunicorn_access\uff0cgunicorn_error\uff09\uff0c\u901a\u8fc7name\u6307\u5b9a\u6355\u83b7\u6a21\u5757\uff0c\u5e76\u53ef\u4ee5\u8bbe\u7f6epropagate\u62e6\u622a\u4e0d\u4f20\u9012\u5230\u5168\u5c40\u65e5\u5fd7\u4e2d\n\n\u4e0d\u8bba\u5168\u5c40\u6216\u5b50\u7ea7\u65e5\u5fd7\u914d\u7f6e\uff0c\u90fd\u53ef\u4ee5\u6307\u5b9a\u4f7f\u7528\u5176\u4ed6handler\uff0c\u5e76\u642d\u914dhandler_args\u81ea\u5b9a\u4e49\u65e5\u5fd7\u4f7f\u7528\u65b9\u5f0f\uff0c\u6307\u5b9a\u7684\u65b9\u5f0f\u4e3a\uff1apackage.module:ClassName\uff0c\u9ed8\u8ba4\u65f6\u6211\u4eec\u4f7f\u7528WatchedFileHandler\uff0c\u56e0\u4e3a\u65e5\u5fd7\u901a\u5e38\u9700\u8981rotate\uff0c\u6211\u4eec\u5e0c\u671b\u65e5\u5fd7\u6a21\u5757\u53ef\u4ee5\u88ab\u65e0\u7f1d\u5207\u5272\u8f6e\u8f6c\u800c\u4e0d\u5f71\u54cd\u5e94\u7528\uff0c\u6240\u4ee5\u8fd9\u4e5f\u662f\u6211\u4eec\u6ca1\u6709\u5c06\u5185\u7f6eHandler\u6307\u5b9a\u4e3aRotatingFileHandler\u7684\u539f\u56e0\uff0c\u7528\u6237\u9700\u8981\u81ea\u5df1\u4f7f\u7528\u64cd\u4f5c\u7cfb\u7edf\u63d0\u4f9b\u7684logrotate\u80fd\u529b\u8fdb\u884c\u914d\u7f6e\u3002\n\n\u4ee5\u4e0b\u662f\u4e00\u4e2a\u5e38\u7528\u7684\u65e5\u5fd7\u914d\u7f6e\uff0c\u5168\u5c40\u65e5\u5fd7\u8bb0\u5f55\u5230server.log\uff0c\u800c\u6a21\u5757cms.apps.filetransfer\u65e5\u5fd7\u5219\u5355\u72ec\u8bb0\u5f55\u5230transfer.log\u6587\u4ef6\uff0c\u76f8\u4e92\u4e0d\u5f71\u54cd\n\n```json\n\"log\": {\n    \"gunicorn_access\": \"./access.log\",\n    \"gunicorn_error\": \"./error.log\",\n    \"path\": \"./server.log\",\n    \"level\": \"INFO\",\n    \"format_string\": \"%(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s:%(lineno)d [-] %(message)s\",\n    \"date_format_string\": \"%Y-%m-%d %H:%M:%S\",\n    \"loggers\": [\n        {\n            \"name\": \"cms.apps.filetransfer\",\n         \t\"level\": \"INFO\",\n         \t\"path\": \"./transfer.log\",\n            \"propagate\": false\n        }\n    ]\n}\n```\n\n\n\n\u5176\u8be6\u7ec6\u53c2\u6570\u8bf4\u660e\u5982\u4e0b\uff1a\n\n| \u8def\u5f84               | \u7c7b\u578b   | \u63cf\u8ff0                                                         | \u9ed8\u8ba4\u503c                                                       |\n| ------------------ | ------ | ------------------------------------------------------------ | ------------------------------------------------------------ |\n| gunicorn_access    | string | \u4f7f\u7528gunicorn\u65f6\uff0caccess\u65e5\u5fd7\u8def\u5f84                               | ./access.log                                                 |\n| gunicorn_error     | string | \u4f7f\u7528gunicorn\u65f6\uff0cerror\u65e5\u5fd7\u8def\u5f84                                | ./error.log                                                  |\n| log_console        | bool   | \u662f\u5426\u5c06\u672c\u65e5\u5fd7\u91cd\u5b9a\u5411\u5230\u6807\u51c6\u8f93\u51fa                                 | True                                                         |\n| path               | string | \u65e5\u5fd7\u8def\u5f84\uff0c\u9ed8\u8ba4\u4f7f\u7528WatchedFileHandler\uff0c\u5f53\u6307\u5b9ahandler\u65f6\u6b64\u9879\u65e0\u6548 | ./server.log                                                 |\n| level              | string | \u65e5\u5fd7\u7ea7\u522b(ERROR\uff0cWARNING\uff0cINFO\uff0cDEBUG)                        | INFO                                                         |\n| handler            | string | \u81ea\u5b9a\u4e49\u7684Logger\u7c7b\uff0ceg: logging.handlers:SysLogHandler\uff0c\u5b9a\u4e49\u6b64\u9879\u540e\u4f1a\u4f18\u5148\u4f7f\u7528\u5e76\u5ffd\u7565\u9ed8\u8ba4\u7684log.path\u53c2\u6570\uff0c\u9700\u8981\u4f7f\u7528handler_args\u8fdb\u884c\u65e5\u5fd7\u521d\u59cb\u5316\u53c2\u6570\u5b9a\u4e49 |                                                              |\n| handler_args       | list   | \u81ea\u5b9a\u4e49\u7684Logger\u7c7b\u7684\u521d\u59cb\u5316\u53c2\u6570\uff0ceg: []                         | []                                                           |\n| format_string      | string | \u65e5\u5fd7\u5b57\u6bb5\u914d\u7f6e                                                 | %(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s:%(lineno)d [-] %(message)s |\n| date_format_string | string | \u65e5\u5fd7\u65f6\u95f4\u683c\u5f0f                                                 | %Y-%m-%d %H:%M:%S                                            |\n| name               | string | \u5168\u5c40log\u4e2d\u65e0\u6b64\u53c2\u6570\uff0c\u4ec5\u7528\u4e8eloggers\u5b50\u65e5\u5fd7\u914d\u7f6e\u5668\u4e0a\uff0c\u8868\u793a\u6355\u83b7\u7684\u65e5\u5fd7\u6a21\u5757\u8def\u5f84 |                                                              |\n| propagate          | bool   | \u5168\u5c40log\u4e2d\u65e0\u6b64\u53c2\u6570\uff0c\u4ec5\u7528\u4e8eloggers\u5b50\u65e5\u5fd7\u914d\u7f6e\u5668\u4e0a\uff0c\u8868\u793a\u65e5\u5fd7\u662f\u5426\u4f20\u9012\u5230\u4e0a\u4e00\u7ea7\u65e5\u5fd7\u8f93\u51fa | True                                                         |\n\n\n\n## \u5de5\u5177\u5e93\n\n### \u5e26\u5bbd\u9650\u901f\n\nlinux\u7cfb\u7edf\u7aef\u53e3\u5e26\u5bbd\u9650\u901f\uff1atalos.common.bandwidth_limiter:BandWidthLimiter\n\n\u4f20\u8f93\u6d41\u5e26\u5bbd\u9650\u901f\uff1a\u672a\u63d0\u4f9b\n\n### \u683c\u5f0f\u8f6c\u6362\n\n#### \u8868\u683c\u5bfc\u51fa\n\ncsv\uff1atalos.common.exporter:export_csv\n\nxlsx\uff1a\u672a\u63d0\u4f9b\n\n#### dict\u8f6cxml\n\ntalos.core.xmlutils:toxml\n\nxmlutils\u4f5c\u4e3acore\u6a21\u5757\u7684\u4e00\u4efd\u5b50\uff0c\u5f88\u91cd\u8981\u7684\u4e00\u70b9\u662f\uff1a\u5fc5\u987b\u4fdd\u8bc1\u8db3\u591f\u7684\u6269\u5c55\u6027\uff0c\u5176\u63d0\u4f9b\u4e86\u81ea\u5b9a\u4e49\u7c7b\u578b\u7684\u8f6c\u6362\u94a9\u5b50\n\n```python\ntest = {'a': 1, 'b': 1.2340932, 'c': True, 'd': None, 'e': 'hello <world />', 'f': {\n    'k': 'v', 'm': 'n'}, 'g': [1, '2', False, None, {'k': 'v', 'm': [1, 2, 3]}],\n    'h': et.Element('root')}\ntoxml(test, \n      attr_type=True,\n      hooks={'etree': {'render': lambda x: x.tag, 'hit': lambda x: isinstance(x, et.Element)}})\n```\n\n\u8f93\u51fa\u7ed3\u679c\uff1a\n\n```xml\n\n```\n\n\u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u6240\u6709\u672a\u5b9a\u4e49\u7684\u7c7b\u578b\uff0c\u90fd\u4f1a\u88abdefault_render\uff08\u5b9e\u9645\u4e0a\u5c31\u662fstr() \uff09\u8fdb\u884c\u8f6c\u6362\u6e32\u67d3\n\nhooks\u4e2d\u5b9a\u4e49\u7684etree\u662f\u4f5c\u4e3axml\u7684\u8282\u70b9type\u5c5e\u6027\u8f93\u51fa\uff0chit\u51fd\u6570\u662f\u7528\u4e8e\u5224\u5b9a\u5b9a\u4e49\u7684\u7c7b\u578b\u5f52\u5c5e\uff0crender\u7528\u4e8e\u63d0\u53d6\u5bf9\u8c61\u5185\u5bb9\n\n\n\n### \u767b\u5f55\u8ba4\u8bc1\n\nLdap\u8ba4\u8bc1\uff1atalos.common.ldap_util:Ldap\n\n\u6388\u6743\u6821\u9a8c\uff1atalos.core.acl:Registry\n\nacl\u6a21\u5757\u63d0\u4f9b\u4e86\u6269\u5c55\u4e8eRBAC\u7684\u6388\u6743\u6a21\u5f0f\uff1apolicy\u6982\u5ff5\u5bf9\u5e94\u89d2\u8272(\u652f\u6301\u89d2\u8272\u7ee7\u627f)\uff0callow/deny\u5bf9\u5e94\u4e00\u4e2a\u6743\u9650\u89c4\u5219\uff0c\u4f20\u7edfRBAC\u5c06\u89d2\u8272\u4e0e\u7528\u6237\u7ed1\u5b9a\u5373\u5b8c\u6210\u6388\u6743\uff0c\u4f46acl\u6a21\u5757\u4e2d\uff0c\u6211\u4eec\u8ba4\u4e3a\u6743\u9650\u4e0d\u662f\u56fa\u5b9a\u7684\uff0c\u5728\u4e0d\u540c\u7684\u573a\u666f\u4e2d\uff0c\u7528\u6237\u53ef\u4ee5\u6709\u4e0d\u540c\u7684\u89d2\u8272\uff0c\u6765\u6267\u884c\u4e0d\u540c\u7684\u52a8\u4f5c\uff0c\u6211\u4eec\u5c06\u573a\u666f\u5b9a\u4e49\u4e3atemplate(\u573a\u666f\u6a21\u677f)\uff0c\u5047\u5b9a\u67d0\u7528\u6237\u5728\u64cd\u4f5c\u5e7f\u5dde\u7684\u8d44\u6e90\u65f6\uff0c\u53ef\u4ee5\u83b7\u5f97\u6700\u5927\u7684admin\u6743\u9650\uff0c\u800c\u64cd\u4f5c\u4e0a\u6d77\u7684\u8d44\u6e90\u65f6\u53ea\u6709readonly\u89d2\u8272\u6743\u9650\n\n```python\naccess = Registry()\naccess.add_policy('readonly')\naccess.add_policy('manage', parents=('readonly',))\naccess.add_policy('admin', parents=('manage',))\naccess.allow('readonly', 'resource.list')\naccess.allow('manage', 'resource.create')\naccess.allow('manage', 'resource.update')\naccess.allow('manage', 'resource.delete')\naccess.allow('admin', 'auth.manage')\n# bind user1 with policies: (GZ, admin), (SH, readonly)\n# get current region: SH\nassert access.is_allowed([('GZ', 'admin'), ('SH', 'readonly')], 'SH', 'resource.create') is not True\n# bind user2 with policies: (*, manage)\n# get current region: SH\nassert access.is_allowed([('*', 'manage')], 'SH', 'resource.create') is True\n```\n\n\u5982\u4e0a\u6240\u793atemplate(\u573a\u666f\u6a21\u677f)\u662f\u53ef\u4ee5\u6a21\u7cca\u5339\u914d\u7684\uff0c\u5176\u9ed8\u8ba4\u5339\u914d\u89c4\u5219\u5982\u4e0b\uff08\u5339\u914d\u51fd\u6570\u53ef\u4ee5\u901a\u8fc7Registry\u66f4\u6539\uff09\uff1a\n\n| Pattern  | Meaning                            |\n| -------- | ---------------------------------- |\n| `*`      | matches everything                 |\n| `?`      | matches any single character       |\n| `[seq]`  | matches any character in *seq*     |\n| `[!seq]` | matches any character not in *seq* |\n\n\u5982\u6b64\u4e00\u6765\u6211\u4eec\u4fbf\u53ef\u4ee5\u4fbf\u6377\u5b9e\u73b0\u4e00\u4e2a\u57fa\u4e8e\u573a\u666f\u7684\u89d2\u8272\u6743\u9650\u6821\u9a8c\u3002\n\n### SMTP\u90ae\u4ef6\u53d1\u9001\n\ntalos.common.mailer:Mailer\n\n### \u5b9e\u7528\u5c0f\u51fd\u6570\n\ntalos.core.utils\n\n## \u914d\u7f6e\u9879\n\ntalos\u63d0\u4f9b\u4e86\u4e00\u4e2a\u7c7b\u5b57\u5178\u7684\u5c5e\u6027\u8bbf\u95ee\u914d\u7f6e\u7c7b\n1. \u5f53\u5c5e\u6027\u662f\u6807\u51c6\u53d8\u91cf\u547d\u540d\u4e14\u975e\u9884\u7559\u51fd\u6570\u540d\u65f6\uff0c\u53ef\u76f4\u63a5a.b.c\u65b9\u5f0f\u8bbf\u95ee\n2. \u5426\u5219\u53ef\u4ee5\u4f7f\u7528a['b-1'].c\u8bbf\u95ee(item\u65b9\u5f0f\u8bbf\u95ee\u65f6\u4f1a\u8fd4\u56deConfig\u5bf9\u8c61)\n3. \u5f53\u5c5e\u6027\u503c\u521a\u597dConfig\u5df2\u5b58\u5728\u51fd\u6570\u76f8\u7b49\u65f6\uff0c\u5c06\u8fdb\u884c\u51fd\u6570\u8c03\u7528\u800c\u975e\u5c5e\u6027\u8bbf\u95ee\uff01\uff01\uff01\n   \u4fdd\u7559\u51fd\u6570\u540d\u5982\u4e0b\uff1aset_options\uff0cfrom_files\uff0citerkeys\uff0citervalues\uff0citeritems\uff0ckeys\uff0cvalues\uff0citems\uff0cget\uff0cto_dict\uff0c_opts\uff0cpython\u9b54\u6cd5\u51fd\u6570\n\n\u6bd4\u5982{\n\u200b        \"my_config\": {\"from_files\": {\"a\": {\"b\": False}}}\n\u200b    }\n\u65e0\u6cd5\u901a\u8fc7CONF.my_config.from_files\u6765\u8bbf\u95ee\u5c5e\u6027\uff0c\u9700\u8981\u7a0d\u4f5c\u8f6c\u6362\uff1aCONF.my_config['from_files'].a.b \u5982\u6b64\u6765\u83b7\u53d6\uff0ctalos\u4f1a\u5728\u9879\u76ee\u542f\u52a8\u65f6\u7ed9\u4e88\u63d0\u793a\uff0c\u8bf7\u60a8\u5173\u6ce8[^ 8]\n\n### \u9884\u6e32\u67d3\u9879\n\ntalos\u4e2d\u9884\u7f6e\u4e86\u5f88\u591a\u63a7\u5236\u7a0b\u5e8f\u884c\u4e3a\u7684\u914d\u7f6e\u9879\uff0c\u53ef\u4ee5\u5141\u8bb8\u7528\u6237\u8fdb\u884c\u76f8\u5173\u7684\u914d\u7f6e\uff1a\u5168\u5c40\u914d\u7f6e\u3001\u542f\u52a8\u670d\u52a1\u914d\u7f6e\u3001\u65e5\u5fd7\u914d\u7f6e\u3001\u6570\u636e\u5e93\u8fde\u63a5\u914d\u7f6e\u3001\u7f13\u5b58\u914d\u7f6e\u3001\u9891\u7387\u9650\u5236\u914d\u7f6e\u3001\u5f02\u6b65\u548c\u56de\u8c03\u914d\u7f6e\n\n\u6b64\u5916\uff0c\u8fd8\u63d0\u4f9b\u4e86\u914d\u7f6e\u9879variables\u62e6\u622a\u9884\u6e32\u67d3\u80fd\u529b[^ 6], \u7528\u6237\u53ef\u4ee5\u5b9a\u4e49\u62e6\u622a\u67d0\u4e9b\u914d\u7f6e\u9879\uff0c\u5e76\u5bf9\u5176\u8fdb\u884c\u4fee\u6539/\u66f4\u65b0\uff08\u5e38\u7528\u4e8e\u5bc6\u7801\u89e3\u5bc6\uff09,\u7136\u540e\u5bf9\u5176\u4ed6\u914d\u7f6e\u9879\u7684\u53d8\u91cf\u8fdb\u884c\u6e32\u67d3\u66ff\u6362\uff0c\u4f7f\u7528\u65b9\u5f0f\u5982\u4e0b\uff1a\n\n```json\n{\n    \"variables\": {\"db_password\": \"MTIzNDU2\", \"other_password\": \"...\"}\n    \"db\": {\"connection\": \"mysql://test:${db_password}@127.0.0.1:1234/db01\"}\n}\n```\n\n\u5982\u4e0a\uff0cvariables\u4e2d\u5b9a\u4e49\u4e86\u5b9a\u4e49\u4e86db_password\u53d8\u91cf(**\u5fc5\u987b\u5728variables\u4e2d\u5b9a\u4e49\u53d8\u91cf**)\uff0c\u5e76\u518ddb.connection\u8fdb\u884c\u53d8\u91cf\u4f7f\u7528(**\u9664variables\u4ee5\u5916\u5176\u4ed6\u914d\u7f6e\u9879\u5747\u53ef\u4f7f\u7528\\${db_password}\u53d8\u91cf\u8fdb\u884c\u5f85\u6e32\u67d3**)\n\n\u5728\u60a8\u81ea\u5df1\u7684\u9879\u76ee\u7684server.wsgi_server \u4ee5\u53ca server.celery_worker\u4ee3\u7801\u5f00\u59cb\u4f4d\u7f6e\u4f7f\u7528\u5982\u4e0b\u62e6\u622a\uff1a\n\n```python\nimport base64\nfrom talos.core import config\n\n@config.intercept('db_password', 'other_password')\ndef get_password(value, origin_value):\n    '''value\u4e3a\u4e0a\u4e00\u4e2a\u62e6\u622a\u5668\u5904\u7406\u540e\u7684\u503c\uff08\u82e5\u6b64\u51fd\u6570\u4e3a\u7b2c\u4e00\u4e2a\u62e6\u622a\u5668\uff0c\u7b49\u4ef7\u4e8eorigin_value\uff09\n       origin_value\u4e3a\u539f\u59cb\u914d\u7f6e\u6587\u4ef6\u7684\u503c\n       \u6ca1\u6709\u62e6\u622a\u7684\u53d8\u91cftalos\u5c06\u81ea\u52a8\u4f7f\u7528\u539f\u59cb\u503c\uff0c\u56e0\u6b64\u5b9a\u4e49\u4e00\u4e2a\u62e6\u622a\u5668\u662f\u5f88\u5173\u952e\u7684\n       \u51fd\u6570\u5904\u7406\u540e\u8981\u6c42\u5fc5\u987b\u8fd4\u56de\u4e00\u4e2a\u503c\n    '''\n    # \u6f14\u793a\u4f7f\u7528\u4e0d\u5b89\u5168\u7684base64\uff0c\u8bf7\u4f7f\u7528\u4f60\u8ba4\u4e3a\u5b89\u5168\u7684\u7b97\u6cd5\u8fdb\u884c\u5904\u7406\n    return base64.b64decode(origin_value)\n\n\n```\n\n> \u4e3a\u4ec0\u4e48\u8981\u5728server.wsgi_server \u4ee5\u53ca server.celery_worker\u4ee3\u7801\u5f00\u59cb\u4f4d\u7f6e\u62e6\u622a\uff1f\n>\n> \u56e0\u4e3a\u914d\u7f6e\u9879\u4e3a\u9884\u6e32\u67d3\uff0c\u5373\u7a0b\u5e8f\u542f\u52a8\u65f6\uff0c\u5c31\u5c06\u914d\u7f6e\u9879\u6b63\u786e\u6e32\u67d3\u5230\u53d8\u91cf\u4e2d\uff0c\u4ee5\u4fbf\u7528\u6237\u4ee3\u7801\u80fd\u53d6\u5230\u6b63\u786e\u7684\u914d\u7f6e\u503c\uff0c\u653e\u5230\u5176\u4ed6\u4f4d\u7f6e\u4f1a\u51fa\u73b0\u90e8\u5206\u4ee3\u7801\u5f97\u5230\u5904\u7406\u524d\u503c\uff0c\u90e8\u5206\u4ee3\u7801\u5f97\u5230\u5904\u7406\u540e\u503c\uff0c\u7ed3\u679c\u5c06\u65e0\u6cd5\u4fdd\u8bc1\u4e00\u81f4\uff0c\u56e0\u6b64server.wsgi_server \u4ee5\u53ca server.celery_worker\u4ee3\u7801\u5f00\u59cb\u4f4d\u7f6e\u8bbe\u7f6e\u62e6\u622a\u662f\u975e\u5e38\u5173\u952e\u7684\n\n\n\n### \u914d\u7f6e\u9879\n\n| \u8def\u5f84                                   | \u7c7b\u578b   | \u63cf\u8ff0                                                         | \u9ed8\u8ba4\u503c                                                       |\n| -------------------------------------- | ------ | ------------------------------------------------------------ | ------------------------------------------------------------ |\n| host                                   | string | \u4e3b\u673a\u540d                                                       | \u5f53\u524d\u4e3b\u673a\u540d                                                   |\n| language                               | string | \u7cfb\u7edf\u8bed\u8a00\u7ffb\u8bd1                                                 | en                                                           |\n| locale_app                             | string | \u56fd\u9645\u5316locale\u5e94\u7528\u540d\u79f0                                         | \u5f53\u524d\u9879\u76ee\u540d                                                   |\n| locale_path                            | string | \u56fd\u9645\u5316locale\u6587\u4ef6\u8def\u5f84                                         | ./etc/locale                                                 |\n| variables                              | dict   | \u53ef\u4f9b\u62e6\u622a\u9884\u6e32\u67d3\u7684\u53d8\u91cf\u540d\u53ca\u5176\u503c                                 | {}                                                           |\n| controller.list_size_limit_enabled     | bool   | \u662f\u5426\u542f\u7528\u5168\u5c40\u5217\u8868\u5927\u5c0f\u9650\u5236                                     | False                                                        |\n| controller.list_size_limit             | int    | \u5168\u5c40\u5217\u8868\u6570\u636e\u5927\u5c0f\uff0c\u5982\u679c\u6ca1\u6709\u8bbe\u7f6e\uff0c\u5219\u9ed8\u8ba4\u8fd4\u56de\u5168\u90e8\uff0c\u5982\u679c\u7528\u6237\u4f20\u5165limit\u53c2\u6570\uff0c\u5219\u4ee5\u7528\u6237\u53c2\u6570\u4e3a\u51c6 | None                                                         |\n| controller.criteria_key.offset         | string | controller\u63a5\u53d7\u7528\u6237\u7684offset\u53c2\u6570\u7684\u5173\u952ekey\u503c                    | __offset                                                     |\n| controller.criteria_key.limit          | string | controller\u63a5\u53d7\u7528\u6237\u7684limit\u53c2\u6570\u7684\u5173\u952ekey\u503c                     | __limit                                                      |\n| controller.criteria_key.orders         | string | controller\u63a5\u53d7\u7528\u6237\u7684orders\u53c2\u6570\u7684\u5173\u952ekey\u503c                    | __orders                                                     |\n| controller.criteria_key.fields         | string | controller\u63a5\u53d7\u7528\u6237\u7684fields\u53c2\u6570\u7684\u5173\u952ekey\u503c                    | __fields                                                     |\n| override_defalut_middlewares           | bool   | \u8986\u76d6\u7cfb\u7edf\u9ed8\u8ba4\u52a0\u8f7d\u7684\u4e2d\u95f4\u4ef6                                     | Flase                                                        |\n| server                                 | dict   | \u670d\u52a1\u76d1\u542c\u914d\u7f6e\u9879                                               |                                                              |\n| server.bind                            | string | \u76d1\u542c\u5730\u5740                                                     | 0.0.0.0                                                      |\n| server.port                            | int    | \u76d1\u542c\u7aef\u53e3                                                     | 9001                                                         |\n| server.backlog                         | int    | \u76d1\u542c\u6700\u5927\u961f\u5217\u6570                                               | 2048                                                         |\n| log                                    | dict   | \u65e5\u5fd7\u914d\u7f6e\u9879                                                   |                                                              |\n| log.log_console                        | bool   | \u662f\u5426\u5c06\u65e5\u5fd7\u91cd\u5b9a\u5411\u5230\u6807\u51c6\u8f93\u51fa                                   | True                                                         |\n| log.gunicorn_access                    | string | gunicorn\u7684access\u65e5\u5fd7\u8def\u5f84                                     | ./access.log                                                 |\n| log.gunicorn_error                     | string | gunicorn\u7684error\u65e5\u5fd7\u8def\u5f84                                      | ./error.log                                                  |\n| log.path                               | string | \u5168\u5c40\u65e5\u5fd7\u8def\u5f84\uff0c\u9ed8\u8ba4\u4f7f\u7528WatchedFileHandler\uff0c\u5f53\u6307\u5b9ahandler\u65f6\u6b64\u9879\u65e0\u6548 | ./server.log                                                 |\n| log.level                              | string | \u65e5\u5fd7\u7ea7\u522b                                                     | INFO                                                         |\n| log.handler[^ 7]                       | string | \u81ea\u5b9a\u4e49\u7684Logger\u7c7b\uff0ceg: logging.handlers:SysLogHandler\uff0c\u5b9a\u4e49\u6b64\u9879\u540e\u4f1a\u4f18\u5148\u4f7f\u7528\u5e76\u5ffd\u7565\u9ed8\u8ba4\u7684log.path |                                                              |\n| log.handler_args[^ 7]                  | list   | \u81ea\u5b9a\u4e49\u7684Logger\u7c7b\u7684\u521d\u59cb\u5316\u53c2\u6570\uff0ceg: []                         |                                                              |\n| log.format_string                      | string | \u65e5\u5fd7\u5b57\u6bb5\u914d\u7f6e                                                 | %(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s:%(lineno)d [-] %(message)s |\n| log.date_format_string                 | string | \u65e5\u5fd7\u65f6\u95f4\u683c\u5f0f                                                 | %Y-%m-%d %H:%M:%S                                            |\n| log.loggers                            | list   | \u6a21\u5757\u72ec\u7acb\u65e5\u5fd7\u914d\u7f6e\uff0c\u5217\u8868\u6bcf\u4e2a\u5143\u7d20\u662fdict: [{\"name\": \"cms.test.api\", \"path\": \"api.log\"}] |                                                              |\n| log.loggers.name                       | string | \u6a21\u5757\u540d\u79f0\u8def\u5f84\uff0c\u5982cms.apps.test\uff0c\u53ef\u4ee5\u88ab\u91cd\u590d\u5b9a\u4e49\u4f7f\u7528            |                                                              |\n| log.loggers.level                      | string | \u53c2\u8003log.level                                                |                                                              |\n| log.loggers.path                       | string | \u53c2\u8003log.path                                                 |                                                              |\n| log.loggers.handler[^ 7]               | string | \u53c2\u8003log.handler                                              |                                                              |\n| log.loggers.handler_args[^ 7]          | list   | \u53c2\u8003log.handler_args                                         |                                                              |\n| log.loggers.propagate[^ 7]             | bool   | \u662f\u5426\u4f20\u9012\u5230\u4e0a\u4e00\u7ea7\u65e5\u5fd7\u914d\u7f6e                                     |                                                              |\n| log.loggers.log_console[^ 7]           | bool   | \u53c2\u8003log.log_console                                          |                                                              |\n| log.loggers.format_string[^ 7]         | string | \u53c2\u8003log.format_string                                        |                                                              |\n| log.loggers.date_format_string[^ 7]    | string | \u53c2\u8003log.date_format_string                                   |                                                              |\n| db                                     | dict   | \u9ed8\u8ba4\u6570\u636e\u5e93\u914d\u7f6e\u9879\uff0c\u7528\u6237\u53ef\u4ee5\u81ea\u884c\u5b9a\u4e49\u5176\u4ed6DB\u914d\u7f6e\u9879\uff0c\u4f46\u9700\u8981\u81ea\u5df1\u521d\u59cb\u5316DBPool\u5bf9\u8c61(\u53ef\u4ee5\u53c2\u8003DefaultDBPool\u8fdb\u884c\u5355\u4f8b\u63a7\u5236) |                                                              |\n| db.connection                          | string | \u8fde\u63a5\u5b57\u7b26\u4e32                                                   |                                                              |\n| db.pool_size                           | int    | \u8fde\u63a5\u6c60\u5927\u5c0f                                                   | 3                                                            |\n| db.pool_recycle                        | int    | \u8fde\u63a5\u6700\u5927\u7a7a\u95f2\u65f6\u95f4\uff0c\u8d85\u8fc7\u65f6\u95f4\u540e\u81ea\u52a8\u56de\u6536                         | 3600                                                         |\n| db.pool_timeout                        | int    | \u83b7\u53d6\u8fde\u63a5\u8d85\u65f6\u65f6\u95f4\uff0c\u5355\u4f4d\u79d2                                     | 5                                                            |\n| db.max_overflow                        | int    | \u7a81\u53d1\u8fde\u63a5\u6c60\u6269\u5c55\u5927\u5c0f                                           | 5                                                            |\n| dbs[^ 7]                               | dict   | \u989d\u5916\u7684\u6570\u636e\u5e93\u914d\u7f6e\u9879\uff0c{name: {db conf...}}\uff0c\u914d\u7f6e\u9879\u4f1a\u88ab\u521d\u59cb\u5316\u5230pool.POOLS\u4e2d\uff0c\u5e76\u4ee5\u540d\u79f0\u4f5c\u4e3a\u5f15\u7528\u540d\uff0c\u793a\u4f8b\u89c1\u8fdb\u9636\u5f00\u53d1->\u591a\u6570\u636e\u5e93\u652f\u6301 |                                                              |\n| dbcrud                                 | dict   | \u6570\u636e\u5e93CRUD\u63a7\u5236\u9879                                             |                                                              |\n| dbcrud.unsupported_filter_as_empty     | bool   | \u5f53\u9047\u5230\u4e0d\u652f\u6301\u7684filter\u65f6\u7684\u9ed8\u8ba4\u884c\u4e3a\uff0c1\u662f\u8fd4\u56de\u7a7a\u7ed3\u679c\uff0c2\u662f\u5ffd\u7565\u4e0d\u652f\u6301\u7684\u6761\u4ef6\uff0c\u7531\u4e8e\u5386\u53f2\u7248\u672c\u7684\u884c\u4e3a\u9ed8\u8ba4\u4e3a2\uff0c\u56e0\u6b64\u5176\u9ed8\u8ba4\u503c\u4e3aFalse\uff0c\u5373\u5ffd\u7565\u4e0d\u652f\u6301\u7684\u6761\u4ef6 | False                                                        |\n| dbcrud.dynamic_relationship            | bool   | \u662f\u5426\u542f\u7528ORM\u7684\u52a8\u6001relationship\u52a0\u8f7d\u6280\u672f\uff0c\u542f\u7528\u540e\u53ef\u4ee5\u901a\u8fc7models.attributes\u6765\u63a7\u5236\u5916\u952e\u52a8\u6001\u52a0\u8f7d\uff0c\u907f\u514d\u6570\u636e\u8fc7\u8f7d\u5bfc\u81f4\u67e5\u8be2\u7f13\u6162 | True                                                         |\n| dbcrud.dynamic_load_method             | string | \u542f\u7528ORM\u7684\u52a8\u6001relationship\u52a0\u8f7d\u6280\u672f\u540e\uff0c\u53ef\u6307\u5b9a\u52a0\u8f7d\u65b9\u5f0f\uff1ajoinedload\uff0csubqueryload\uff0cselectinload\uff0cimmediateload<br/>**joinedload**\uff1a\u4f7f\u7528outer join\u5c06\u6240\u6709\u67e5\u8be2\u8fde\u63a5\u4e3a\u4e00\u4e2a\u8bed\u53e5\uff0c\u7ed3\u679c\u96c6\u5c11\u65f6\u901f\u5ea6\u6700\u5feb\uff0c\u968f\u7740\u7ed3\u679c\u96c6\u548c\u7ea7\u8054\u5916\u952e\u6570\u91cf\u7684\u589e\u52a0\uff0c\u5b57\u6bb5\u7684\u5c55\u5f00\u4f1a\u5bfc\u81f4\u6570\u636e\u6781\u5927\u800c\u52a0\u8f7d\u7f13\u6162<br/>**subqueryload**\uff1a\u6bd4\u8f83\u6298\u4e2d\u7684\u65b9\u5f0f\uff0c\u4f7f\u7528\u5916\u952e\u72ec\u7acbsql\u67e5\u8be2\uff0c\u7ed3\u679c\u96c6\u5c11\u65f6\u901f\u5ea6\u8f83\u5feb\uff0c\u968f\u7740\u7ed3\u679c\u96c6\u548c\u7ea7\u8054\u5916\u952e\u6570\u91cf\u7684\u589e\u52a0\uff0c\u901f\u5ea6\u9010\u6b65\u4f18\u4e8ejoinedload<br/>**selectinload**\uff1a\u7c7b\u4f3csubqueryload\uff0c\u4f46\u6bcf\u4e2a\u67e5\u8be2\u4f7f\u7528\u7ed3\u679c\u96c6\u7684\u4e3b\u952e\u7ec4\u5408\u4e3ain\u67e5\u8be2\uff0c\u901f\u5ea6\u6162<br/>**immediateload**\uff1a\u7c7b\u4f3cSQLAlchemy\u7684select\u61d2\u52a0\u8f7d\uff0c\u6bcf\u884c\u7684\u5916\u952e\u5355\u72ec\u4f7f\u7528\u4e00\u4e2a\u67e5\u8be2\uff0c\u901f\u5ea6\u6700\u6162<br/> | joinedload                                                   |\n| dbcrud.detail_relationship_as_summary  | bool   | \u63a7\u5236\u83b7\u53d6\u8be6\u60c5\u65f6\uff0c\u4e0b\u7ea7relationship\u662f\u5217\u8868\u7ea7\u6216\u6458\u8981\u7ea7\uff0cFalse\u4e3a\u5217\u8868\u7ea7\uff0cTrue\u4e3a\u6458\u8981\u7ea7\uff0c\u9ed8\u8ba4False | False                                                        |\n| cache                                  | dict   | \u7f13\u5b58\u914d\u7f6e\u9879                                                   |                                                              |\n| cache.type                             | string | \u7f13\u5b58\u540e\u7aef\u7c7b\u578b                                                 | dogpile.cache.memory                                         |\n| cache.expiration_time                  | int    | \u7f13\u5b58\u9ed8\u8ba4\u8d85\u65f6\u65f6\u95f4\uff0c\u5355\u4f4d\u4e3a\u79d2                                   | 3600                                                         |\n| cache.arguments                        | dict   | \u7f13\u5b58\u989d\u5916\u914d\u7f6e                                                 | None                                                         |\n| application                            | dict   |                                                              |                                                              |\n| application.names                      | list   | \u52a0\u8f7d\u7684\u5e94\u7528\u5217\u8868\uff0c\u6bcf\u4e2a\u5143\u7d20\u4e3astring\uff0c\u4ee3\u8868\u52a0\u8f7d\u7684app\u8def\u5f84          | []                                                           |\n| rate_limit                             | dict   | \u9891\u7387\u9650\u5236\u914d\u7f6e\u9879                                               |                                                              |\n| rate_limit.enabled                     | bool   | \u662f\u5426\u542f\u7528\u9891\u7387\u9650\u5236                                             | False                                                        |\n| rate_limit.storage_url                 | string | \u9891\u7387\u9650\u5236\u6570\u636e\u5b58\u50a8\u8ba1\u7b97\u540e\u7aef                                     | memory://                                                    |\n| rate_limit.strategy                    | string | \u9891\u7387\u9650\u5236\u7b97\u6cd5\uff0c\u53ef\u9009fixed-window\uff0cfixed-window-elastic-expiry\uff0cmoving-window | fixed-window                                                 |\n| rate_limit.global_limits               | string | \u5168\u5c40\u9891\u7387\u9650\u5236(\u4f9d\u8d56\u4e8e\u5168\u5c40\u4e2d\u95f4\u4ef6)\uff0ceg. 1/second; 5/minute       | None                                                         |\n| rate_limit.per_method                  | bool   | \u662f\u5426\u4e3a\u6bcf\u4e2aHTTP\u65b9\u6cd5\u72ec\u7acb\u9891\u7387\u9650\u5236                               | True                                                         |\n| rate_limit.header_reset                | string | HTTP\u54cd\u5e94\u5934\uff0c\u9891\u7387\u91cd\u7f6e\u65f6\u95f4                                     | X-RateLimit-Reset                                            |\n| rate_limit.header_remaining            | string | HTTP\u54cd\u5e94\u5934\uff0c\u5269\u4f59\u7684\u8bbf\u95ee\u6b21\u6570                                   | X-RateLimit-Remaining                                        |\n| rate_limit.header_limit                | string | HTTP\u54cd\u5e94\u5934\uff0c\u6700\u5927\u8bbf\u95ee\u6b21\u6570                                     | X-RateLimit-Limit                                            |\n| celery                                 | dict   | \u5f02\u6b65\u4efb\u52a1\u914d\u7f6e\u9879                                               |                                                              |\n| celery.talos_on_user_schedules_changed | list   | \u5b9a\u65f6\u4efb\u52a1\u53d8\u66f4\u5224\u65ad\u51fd\u6570\u5217\u8868\"talos_on_user_schedules_changed\":[\"cms.workers.hooks:ChangeDetection\"], |                                                              |\n| celery.talos_on_user_schedules         | list   | \u5b9a\u65f6\u4efb\u52a1\u51fd\u6570\u5217\u8868\"talos_on_user_schedules\": [\"cms.workers.hooks:AllSchedules\"] |                                                              |\n| worker                                 | dict   | \u5f02\u6b65\u5de5\u4f5c\u8fdb\u7a0b\u914d\u7f6e\u9879                                           |                                                              |\n| worker.callback                        | dict   | \u5f02\u6b65\u5de5\u4f5c\u8fdb\u7a0b\u56de\u8c03\u63a7\u5236\u914d\u7f6e\u9879                                   |                                                              |\n| worker.callback.strict_client          | bool   | \u5f02\u6b65\u5de5\u4f5c\u8fdb\u7a0b\u8ba4\u8bc1\u65f6\u4ec5\u4f7f\u7528\u76f4\u8fdeIP                               | True                                                         |\n| worker.callback.allow_hosts            | list   | \u5f02\u6b65\u5de5\u4f5c\u8fdb\u7a0b\u8ba4\u8bc1\u4e3b\u673aIP\u5217\u8868\uff0c\u5f53\u8bbe\u7f6e\u65f6\uff0c\u4ec5\u5141\u8bb8\u5217\u8868\u5185worker\u8c03\u7528\u56de\u8c03 | None                                                         |\n| worker.callback.name.%s.allow_hosts    | list   | \u5f02\u6b65\u5de5\u4f5c\u8fdb\u7a0b\u8ba4\u8bc1\u65f6\uff0c\u4ec5\u5141\u8bb8\u5217\u8868\u5185worker\u8c03\u7528\u6b64\u547d\u540d\u56de\u8c03         | None                                                         |\n\n\n\n## CHANGELOG\n\n1.3.6:\n\n- \u66f4\u65b0\uff1a[crud] relationship\u7684\u591a\u5c5e\u6027 & \u591a\u7ea7\u5d4c\u5957 \u67e5\u8be2\u652f\u6301\n- \u4fee\u590d\uff1a[utils] http\u6a21\u5757\u7684i18n\u652f\u6301\n\n1.3.5:\n\n- \u4fee\u590d\uff1a[crud] _addtional_update\u7684after_update\u53c2\u6570\u53d6\u503c\u65e0\u6548\u95ee\u9898\n\n1.3.4:\n- \u4fee\u590d\uff1a[crud] update & delete\u65f6\u5e26\u5165default_orders\u62a5\u9519\u95ee\u9898\n\n1.3.3:\n\n- \u66f4\u65b0\uff1a[config] \u4f18\u5316config.item\u6548\u7387\n- \u66f4\u65b0\uff1a[crud] \u4f18\u5316deepcopy\u5bfc\u81f4\u7684\u6548\u7387\u95ee\u9898\n- \u66f4\u65b0\uff1a[utils] \u4f18\u5316utils.get_function_name\u6548\u7387\n- \u66f4\u65b0\uff1a[crud] \u63d0\u4f9bregister_filter\u652f\u6301\u5916\u90e8filter\u6ce8\u518c\n- \u4fee\u590d\uff1a[crud] any_orm_data\u8fd4\u56de\u5b57\u6bb5\u4e0d\u6b63\u786e\u95ee\u9898\n\n1.3.2:\n\n- \u66f4\u65b0\uff1a[i18n] \u652f\u6301\u591a\u8bed\u8a00\u5305\u52a0\u8f7d\uff0c\u5e76\u9ed8\u8ba4\u7b2c\u4e00\u8bed\u8a00\uff08language: [en, zh, zh-CN,...]\uff09\n- \u4fee\u590d\uff1a[crud] update relationship\u540e\u8fd4\u56de\u7684\u5bf9\u8c61\u4e0d\u662f\u6700\u65b0\u4fe1\u606f\u95ee\u9898\n\n1.3.1:\n\n- \u66f4\u65b0\uff1a[db] models\u52a8\u6001relationship\u52a0\u8f7d\uff0c\u6548\u7387\u63d0\u5347(CONF.dbcrud.dynamic_relationship\uff0c\u9ed8\u8ba4\u5df2\u542f\u7528)\uff0c\u5e76\u53ef\u4ee5\u6307\u5b9aload\u65b9\u5f0f(\u9ed8\u8ba4joinedload)\n\n- \u66f4\u65b0\uff1a[db] \u652f\u6301\u8bbe\u5b9a\u83b7\u53d6\u8d44\u6e90detail\u7ea7\u65f6\u4e0b\u7ea7relationship\u6307\u5b9a\u5217\u8868\u7ea7 / \u6458\u8981\u7ea7(CONF.dbcrud.detail_relationship_as_summary)\n\n- \u66f4\u65b0\uff1a[test]\u52a8\u6001relationship\u52a0\u8f7d/\u88c5\u9970\u5668/\u5f02\u5e38/\u7f13\u5b58/\u5bfc\u51fa/\u6821\u9a8c\u5668/\u63a7\u5236\u5668\u6a21\u5757\u7b49\u5927\u91cf\u5355\u5143\u6d4b\u8bd5\n\n- \u66f4\u65b0**[breaking]**\uff1a[controller]_build_criteria\u7684supported_filters\u7531fnmatch\u66f4\u6539\u4e3are\u5339\u914d\u65b9\u5f0f\n  > \u7531fnmatch\u66f4\u6539\u4e3are\u5339\u914d\uff0c\u63d0\u5347\u6548\u7387\uff0c\u4e5f\u63d0\u9ad8\u4e86\u5339\u914d\u81ea\u7531\u5ea6\n  >\n  > \u5982\u679c\u60a8\u7684\u9879\u76ee\u4e2d\u4f7f\u7528\u4e86supported_filters=['name\\_\\_\\*']\u7c7b\u4f3c\u7684\u6307\u5b9a\u652f\u6301\u53c2\u6570\uff0c\u9700\u8981\u540c\u6b65\u66f4\u65b0\u4ee3\u7801\u5982\uff1a['name\\_\\_.\\*']\n  >\n  > \u5982\u679c\u4ec5\u4f7f\u7528\u8fc7supported_filters=['name']\u7c7b\u7684\u6307\u5b9a\u652f\u6301\u53c2\u6570\uff0c\u5219\u4f9d\u7136\u517c\u5bb9\u65e0\u9700\u66f4\u6539\n\n- \u66f4\u65b0\uff1a[controller]_build_criteria\u652f\u6301unsupported_filter_as_empty\u914d\u7f6e(\u542f\u7528\u65f6\uff0c\u4e0d\u652f\u6301\u53c2\u6570\u5c06\u5bfc\u81f4\u51fd\u6570\u8fd4\u56deNone)\n\n- \u66f4\u65b0\uff1a[controller]\u589e\u52a0redirect\u91cd\u5b9a\u5411\u51fd\u6570\n\n- \u4fee\u590d\uff1a[controller]\u652f\u6301\u539f\u751ffalcon\u7684raise HTTPTemporaryRedirect(...)\u5f62\u5f0f\u91cd\u5b9a\u5411\n\n- \u4fee\u590d\uff1a[util] xmlutils\u7684py2/py3\u517c\u5bb9\u95ee\u9898\n\n- \u4fee\u590d\uff1a[schedule] TScheduler\u6982\u7387\u4e22\u5931\u4e00\u4e2amax_interval\u65f6\u95f4\u6bb5\u5b9a\u65f6\u4efb\u52a1\u95ee\u9898\n\n- \u4fee\u590d\uff1a[middleware]falcon>=2.0 \u4e14\u4f7f\u7528wsgiref.simple_server\u65f6block\u95ee\u9898\n\n1.3.0:\n\n- \u65b0\u589e\uff1a[db] \u591a\u6570\u636e\u5e93\u8fde\u63a5\u6c60\u914d\u7f6e\u652f\u6301(CONF.dbs)\n- \u65b0\u589e\uff1a[worker] \u8fdc\u7a0b\u8c03\u7528\u5feb\u6377\u6a21\u5f0f(callback.remote(...))\n- \u65b0\u589e\uff1a[cache] \u57fa\u4e8eredis\u7684\u5206\u5e03\u5f0f\u9501\u652f\u6301(cache.distributed_lock)\n- \u65b0\u589e\uff1a[exception] \u629b\u51fa\u5f02\u5e38\u53ef\u643a\u5e26\u989d\u5916\u6570\u636e(raise Error(exception_data=...),  e.to_dict())\n- \u66f4\u65b0\uff1a[exception] \u9ed8\u8ba4\u6355\u83b7\u6240\u6709\u5f02\u5e38\uff0c\u8fd4\u56de\u7edf\u4e00\u5f02\u5e38\u7ed3\u6784\n- \u66f4\u65b0\uff1a[exception] \u66ff\u6362\u5f02\u5e38\u5e8f\u5217\u5316to_xml\u5e93\uff0c\u7531dicttoxml\u5e93\u66f4\u6362\u4e3atalos.core.xmlutils\uff0c\u63d0\u5347\u6548\u7387\uff0c\u652f\u6301\u66f4\u591a\u6269\u5c55\n- \u66f4\u65b0\uff1a[template] \u751f\u6210\u6a21\u677f\uff1arequirements\uff0cwsgi_server\uff0ccelery_worker\n- \u66f4\u65b0\uff1a[base] \u652f\u6301falcon 2.0\n- \u66f4\u65b0\uff1a[log] \u652f\u6301\u81ea\u5b9a\u4e49handler\u7684log\u914d\u7f6e\n- \u66f4\u65b0\uff1a[util] \u652f\u6301\u534f\u7a0b\u7ea7\u522b\u7684GLOABLS(\u652f\u6301thread/gevent/eventlet\u7c7b\u578b\u7684worker)\n- \u4fee\u590d\uff1a[base] \u5355\u5143\u7d20\u7684query\u6570\u7ec4\u9519\u8bef\u89e3\u6790\u4e3a\u4e00\u4e2a\u5143\u7d20\u800c\u975e\u6570\u7ec4\u95ee\u9898\n- \u4fee\u590d\uff1a[util] exporter\u5bf9\u5f02\u5e38\u7f16\u7801\u7684\u517c\u5bb9\u95ee\u9898\n- \u4fee\u590d\uff1a[crud] create/update\u91cd\u590d\u6821\u9a8c\u8f93\u5165\u503c\n\n1.2.3:\n\n- \u4f18\u5316\uff1a[config] \u652f\u6301\u914d\u7f6e\u9879\u53d8\u91cf/\u62e6\u622a/\u9884\u6e32\u67d3(\u5e38\u7528\u4e8e\u914d\u7f6e\u9879\u7684\u52a0\u89e3\u5bc6) \n\n1.2.2:\n\n- \u4f18\u5316\uff1a[util] \u9891\u7387\u9650\u5236\uff0c\u652f\u6301\u7c7b\u7ea7/\u51fd\u6570\u7ea7\u9891\u7387\u9650\u5236\uff0c\u66f4\u591a\u590d\u6742\u573a\u666f \n- \u4f18\u5316\uff1a[test] \u5b8c\u5584\u5355\u5143\u6d4b\u8bd5 \n- \u4f18\u5316\uff1a[base] JSONB\u590d\u6742\u67e5\u8be2\u652f\u6301 \n- \u4f18\u5316\uff1a[base] \u4e00\u4e9b\u5c0f\u7ec6\u8282\n\n1.2.1\uff1a\n- \u89c1 [tags](https://gitee.com/wu.jianjun/talos/tags)\n\n...\n\n\n\n[^ 1]: \u672c\u6587\u6863\u57fa\u4e8ev1.1.8\u7248\u672c\uff0c\u5e76\u589e\u52a0\u4e86\u540e\u7eed\u7248\u672c\u7684\u4e00\u4e9b\u7279\u6027\u63cf\u8ff0\n[^ 2]: v1.1.9\u7248\u672c\u4e2d\u65b0\u589e\u4e86TScheduler\u652f\u6301\u52a8\u6001\u7684\u5b9a\u65f6\u4efb\u52a1\u4ee5\u53ca\u66f4\u4e30\u5bcc\u7684\u914d\u7f6e\u5b9a\u4e49\u5b9a\u65f6\u4efb\u52a1\n[^ 3]: v1.1.8\u7248\u672c\u4e2d\u4ec5\u652f\u6301\u8fd9\u7c7b\u7b80\u5355\u7684\u5b9a\u65f6\u4efb\u52a1\n[^ 4]: v1.2.0\u7248\u672c\u589e\u52a0\u4e86__fields\u5b57\u6bb5\u9009\u62e9 \u4ee5\u53ca null, notnull, nlike, nilike\u7684\u67e5\u8be2\u6761\u4ef6 \u4ee5\u53ca relationship\u67e5\u8be2\u652f\u6301\n[^ 5]: v1.2.0\u7248\u672c\u65b0\u589e\\$or,\\$and\u67e5\u8be2\u652f\u6301\n[^ 6]: v1.2.3\u7248\u672c\u540e\u5f00\u59cb\u652f\u6301\n[^ 7]: v1.3.0\u7248\u672c\u65b0\u589e\u591a\u6570\u636e\u5e93\u8fde\u63a5\u6c60\u652f\u6301\u4ee5\u53ca\u65e5\u5fd7handler\u9009\u9879\n[^ 8]: v1.3.0\u7248\u672c\u65b0\u589e\u4e86Config\u9879\u52a0\u8f7d\u65f6\u7684warnings\uff0c\u4ee5\u63d0\u9192\u7528\u6237\u6b64\u914d\u7f6e\u9879\u6b63\u786e\u8bbf\u95ee\u65b9\u5f0f\n[^ 9]: v1.3.1\u7248\u672c\u66f4\u65b0\u4e86relationship\u7684\u52a8\u6001\u52a0\u8f7d\u6280\u672f\uff0c\u53ef\u6839\u636e\u8bbe\u5b9a\u7684attributes\u81ea\u52a8\u52a0\u901f\u67e5\u8be2(\u9ed8\u8ba4\u542f\u7528)\n",
    "bugtrack_url": null,
    "license": "Apache License 2.0",
    "summary": "A Falcon Base, Powerful RESTful API Framework, with SQLAlchemy integrated",
    "version": "1.3.7",
    "project_urls": {
        "Homepage": "https://gitee.com/wu.jianjun/talos"
    },
    "split_keywords": [
        "talos",
        "automation",
        "restful",
        "rest",
        "api",
        "celery",
        "sqlalchemy",
        "falcon"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "27e68d505a7df0bec2b9ee6db67c83b10a389a310446a4220f7e81f9ba6033dd",
                "md5": "e25b1ad51925d2b3664e26c2fab8e0b6",
                "sha256": "4a34727675c00db899394f9fdae57e256defa7a61fb4db1899fe274826bab3fe"
            },
            "downloads": -1,
            "filename": "talos_api-1.3.7-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e25b1ad51925d2b3664e26c2fab8e0b6",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 127706,
            "upload_time": "2024-10-15T02:51:07",
            "upload_time_iso_8601": "2024-10-15T02:51:07.920190Z",
            "url": "https://files.pythonhosted.org/packages/27/e6/8d505a7df0bec2b9ee6db67c83b10a389a310446a4220f7e81f9ba6033dd/talos_api-1.3.7-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bf2688c8908169c43d6885544f9579fee02fc35670a093f5ab55a0ea3e5ee397",
                "md5": "195e5553f58b73477cc5c69f2b7fc3fb",
                "sha256": "ae682aa975d14c12825f34b7334421f71cfc35e74c5c25ddc77131bbc21f752a"
            },
            "downloads": -1,
            "filename": "talos-api-1.3.7.tar.gz",
            "has_sig": false,
            "md5_digest": "195e5553f58b73477cc5c69f2b7fc3fb",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 175398,
            "upload_time": "2024-10-15T02:51:10",
            "upload_time_iso_8601": "2024-10-15T02:51:10.677528Z",
            "url": "https://files.pythonhosted.org/packages/bf/26/88c8908169c43d6885544f9579fee02fc35670a093f5ab55a0ea3e5ee397/talos-api-1.3.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-15 02:51:10",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "talos-api"
}
        
Roy
Elapsed time: 0.38550s