我想建立一个库,将建立一个API的XML响应。为了帮助说明我的问题,以下是2个示例API响应。第一个显示菜单,第二个显示文本。Python的API包装设计模式
<CiscoIPPhoneMenu>
<Title>Title text goes here</Title>
<Prompt>Prompt text goes here</Prompt>
<MenuItem>
<Name>The name of each menu item</Name>
<URL>The URL associated with the menu item</URL>
</MenuItem>
<SoftKeyItem>
<Name>Name of soft key</Name>
<URL>URL or URI of soft key</URL>
<Position>Position information of the soft key</Position>
</SoftKeyItem>
</CiscoIPPhoneMenu>
...
<CiscoIPPhoneText>
<Title>Title text goes here</Title>
<Prompt>The prompt text goes here</Prompt>
<Text>The text to be displayed as the message body goes here</Text>
<SoftKeyItem>
<Name>Name of soft key</Name>
<URL>URL or URI of soft key</URL>
<Position>Position information of the soft key</Position>
<SoftKeyItem>
</CiscoIPPhoneText>
好了,所以我的模块轮廓如下:
class CiscoIPPhone(object):
def __init__(self, title=None, prompt=None):
self.title = title
self.prompt = prompt
class MenuItem(object):
def __init__(self, name, url):
self.name = name
self.url = url
class CiscoIPPhoneMenu(CiscoIPPhone):
def __init__(self, *args, **kwargs):
super(CiscoIPPhoneMenu, self).__init__(*args, **kwargs)
self.items = []
def add_menu(self, name, url):
self.items.append(MenuItem(name, url))
注:为便于阅读,我删除了验证和消毒这些类处理。
所以我的问题是:
- 我几乎输出这些对象的序列化表示,这样做是这个算错了还是不好的做法?
- 是否有描述这种API接口类的设计模式?
- 是否有一个Python库可以做类似的优雅编写(Pythonic)? (我正在考虑像Django模型序列化的精简版本,或者Django-Tastypie)。