用于编写plantuml序列图的python dsl
napkin的Python项目详细描述
餐巾
餐巾纸是一种工具,可以像python代码一样有效地“编写”序列图。
动机
序列图是捕获 设计。PlantUML是绘制好序列的好工具 具有简单的人类可读纯文本的图表。
但是,当存在嵌套调用时,PlantUML的语法很难使用, 涉及多个激活/停用的生命线。 不幸的是,这种情况在软件序列图中很常见。
例如,考虑下面的公共序列图,
来自Figure 4.2, UML Distilled 3E:
图表的简单UML脚本如下:
@startuml participant User participant Order participant OrderLine participant Product participant Customer User -> Order : calculatePrice() activate Order Order -> OrderLine : calculatePrice() activate OrderLine OrderLine -> Product : getPrice(quantity:number) OrderLine -> Customer : getDiscountedValue(Order) activate Customer Customer -> Order : getBaseValue() activate Order Customer <-- Order: value deactivate Order OrderLine <-- Customer: discountedValue deactivate Customer deactivate OrderLine deactivate Order @enduml
这是很难遵循的,尤其是有多层次的嵌套作用/失活
如果我们用下面的python代码来表达同样的内容呢?
@napkin.seq_diagram()defdistributed_control(c):user=c.object('User')order=c.object('Order')orderLine=c.object('OrderLine')product=c.object('Product')customer=c.object('Customer')withuser:withorder.calculatePrice():withorderLine.calculatePrice():product.getPrice('quantity:number')withcustomer.getDiscountedValue(order):order.getBaseValue().ret('value')c.ret('discountedValue')
distributed_control
是接受上下文对象的普通函数,c
来访问api。
函数定义对象,控件以user
对象开始,然后调用orderLine.calculatePrice()
。
基本上,序列图表示为“几乎”正常的python代码。
使用python而不是使用其他特殊的 语法语言:
- 易于编写/维护正确图表的脚本
- 许多常见的错误被检测为普通的python错误。例如,方法 对未定义对象的调用将是正常的python错误(这可能是偶数)。 由IDE检查,不运行脚本)。
- 任何python编辑器都可以成为序列图编辑器
- 利用python的通用性可以有很多有趣的用法 语言。例如,我们可以为模式构建一个库。
安装
使用pip
pip install napkin
你好,世界
编写一个名为hello.py
的简单脚本,如下所示:
importnapkin@napkin.seq_diagram()defhello_world(c):user=c.object('user')world=c.object('world')withuser:world.hello()
然后,下面的命令将生成hello_world.puml
:
$ napkin hello.py
用法
命令行
usage: napkin [-h] [--output-format {plantuml,plantuml_png}]
[--output-dir OUTPUT_DIR] [--version]
srcs [srcs ...]
positional arguments:
srcs Python file or directory containing diagram functions
optional arguments:
-h, --help show this help message and exit
--output-format {plantuml,plantuml_png}, -f {plantuml,plantuml_png}
--output-dir OUTPUT_DIR, -o OUTPUT_DIR
--version show program's version number and exit
Supported output formats:
plantuml : PlantUML script (default)
plantuml_png : PlantUML script and PNG image
生成图表的独立代码
我们不必传递napkin
二进制python文件,只需运行
包含以下图表的python源代码:
importnapkin@napkin.seq_diagram()defhello_world(c):...if__name__=='__main__':napkin.generate()
napkin.generate(output_format='plantuml', output_dir='.')
将生成同一文件中描述的所有关系图。
直接生成PNG文件
餐巾纸可以使用plantuml Python package直接生成png-formt图像文件。
安装可选软件包后,请执行以下操作:
$ pip install plantuml
napkin
可以用plantuml_png
指定输出格式,它将与puml文件一起生成png文件。
$ napkin -f plantuml_png hello.py