🦋
Butterfly 用户手册
  • Introduction
  • 一 前言
  • 二 开始
    • 安装部署
    • 五分钟体验指南
    • 单机使用手册
    • 应用规范
      • handler specs
      • middleware specs
      • xingqiao_plugin specs
      • yiqiu_program specs
  • 三 客户端功能
    • MySQL 原生协议
    • MySQL ORM
    • Redis 原生协议
      • redis_config
      • redis_tls
    • Redis ORM
    • Redis mcpack
    • Localcache
    • Kazoo
  • 四 应用(通用服务)
    • API JSON 规范
    • 异步任务 BaiChuan(百川)
    • 任务调度 RuQi(如期)
    • 任务编排 XingQiao(星桥)
    • 配置管理 WuXing(五行)
    • 运筹决策 BaiCe(百策)
  • 五 部署运维
    • 单机容器化部署
    • 监控
    • 异常排查
      • CPU Load spike every 7 hours
    • 升级
    • 安全
    • 其他
  • 六 前端
    • butterfly_template
    • butterfly_fe
    • butterfly-admin(json2web)
      • amis
      • sso
      • pangu
    • NoahV
    • PyWebIO
  • 七 潘多拉魔盒
    • 装饰器
      • localcache_decorator
      • retry_decorator
      • custom_decorator
      • command2http_decorator
    • 算法
      • 算法-分位数
      • 算法-变异系数
    • 实用工具
      • host_util
      • shell_util
      • http_util
      • time_util
      • random_util
      • concurrent
      • jsonschema
      • blinker
      • toml
      • command_util
      • config_util
      • picobox
      • 对称加密
        • des
        • aes
      • ascii_art
        • ttable
        • chart
      • business_rules
      • python-mysql-replication
      • dict_util
    • 中间件
      • middleware_status
      • middleware_whitelist
    • test_handler.py
  • 八 最佳实践
    • 分布式架构
    • Code practice
    • Log practice
    • Daemon process
  • 附录
Powered by GitBook
On this page
  • 1 Python
  • 1.1 避免魔术数字
  • 1.2 不要预计算字面量表达式
  • 1.3 优先使用列表推导或内联函数
  • 1.4 当在非测试代码中使用 assert 时,妥善添加断言信息
  • 2 Butterfly
  • 2.1 command 执行时默认展示 table,接口请求时展示 json
  1. 八 最佳实践

Code practice

Previous分布式架构NextLog practice

Last updated 1 month ago

1 Python

1.1 避免魔术数字

不要在代码中出现

# BAD
if cluster_type == 1:
    pass


# GOOD
class enum_cluster_type(object):
    """"""
    K8S = 1
    Mesos = 2

if cluster_type == enum_cluster_type.K8S:
    pass

1.2 不要预计算字面量表达式

如果某个变量是通过简单算式得到的,应该保留算式内容。不要直接使用计算后的结果。

# BAD
if delta_seconds > 950400:
    return

# GOOD
if delta_seconds > 11 * 24 * 3600:
    return

1.3 优先使用列表推导或内联函数

使用列表推导或内联函数能够清晰知道要生成一个列表,并且更简洁

# BAD
list_two = []
for v in list_one:
    if v[0]:
        new_list.append(v[1])

# GOOD one
list_two = [v[1] for v in list_one if v[0]]

# GOOD two
list_two = list(filter(lambda x: x[0], list_one))

1.4 当在非测试代码中使用 assert 时,妥善添加断言信息

>>> assert 1 == 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

在大段的日志中,单独存在的 AssertionError 不利于日志检索和问题定位,所以添加上可读的断言信息是更推荐的做法。

# BAD
assert "hello" == "world"

# GOOD
assert "hello" == "world", "Hello is not equal to world"

eg:

assert isinstance(req, Request), "req must request"

2 Butterfly

2.1 command 执行时默认展示 table,接口请求时展示 json

参数默认值设置为 "table",程序内部判断当前请求方式

if req.wsgienv.get("REQUEST_METHOD", "COMMAND") != "COMMAND":
    display = "json"
Magic Number