交互协定 status_code.py
理论背景
# 使用时直接使用变量名,含义更清晰
PREPARE = 0
GET_TASK = 1
DO_TASK = 2
CLEAN_UP = 3源码分析
# 定义原始数据结构
_codes = {
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
404: ('not_found', '-o-'),
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
}
# codes全局变量,LookupDick对象,codes.okay或codes['okay'] 都行
codes = LookupDict(name='status_codes')
# 因requests/__init__.py中from .status_codes import codes,所以会执行该模块代码
def _init():
for code, titles in _codes.items():
for title in titles:
setattr(codes, title, code)
if not title.startswith(('\\', '/')):
setattr(codes, title.upper(), code)
# 导入时已触发执行: 全局变量codes经过setattr把所有短语和状态码进行绑定
_init()项目实践
1. API通用返回格式
2. 函数之间标识符
3. 多人之间协议
Last updated