# status.py
class Status(object):
@classmethod
def add(cls, title, kind, attachment):
self.db.set('title', title)
self.db.set('kind', kind)
self.db.set('attachment', attachment)
def add_text_status(title, text):
Status.add(title, 'text', {
'text': text
})
def add_photo_status(title, photos):
Status.add(title, 'photos', {
'photos': photos
})
def add_video_status(title, video_url):
Status.add(title, 'video', {
'url': video_url
})
...
# view.py
@app.route('/add')
def add_status(request):
title = request.get('title')
kind = request.get('kind')
if kind == 'text':
text = request.get('text')
status = add_text_status(title, kind, text)
elif kind == 'photos':
photo_ids = request.get('photo_ids')
photos = Photo.gets(photo_ids)
status = add_photo_status(title, kind, photos)
elif kind == 'video':
video_url = request.get('video_url')
status = add_video_status(title, kind, video_url)
elif ....
return status.to_json()
嗨,有没有办法通过删除if elif elif elif
中的view.py
代码来改进此代码?
答案 0 :(得分:6)
您可以使用方法调度:
def process_text_status(request, title):
text = request.get('text')
status = add_text_status(title, kind, text)
def process_photo_status(request, title):
photo_ids = request.get('photo_ids')
photos = Photo.gets(photo_ids)
status = add_photo_status(title, kind, photos)
process_kind_status = {
'text': process_text_status,
'photos': process_photo_status,
}
@app.route('/add')
def add_status(request):
title = request.get('title')
kind = request.get('kind')
process_kind_status[kind](request, title)
或将process_*_status
功能合并到add_*_status
。