python实现简单服务器(三)

上一篇文章中我们可以在do_GET那冗长的if-elif-else判断里再加一个判断请求地址是不是根地址的分支,也许我们可以找到一个更加聪明的方法。

比如说把每一种情况都单独写成一个条件类:

class case_no_file(object):
 '''该路径不存在'''
 def test(self, handler):
 return not os.path.exists(handler.full_path)
 def act(self, handler):
 raise ServerException("'{0}' not found".format(handler.path))
class case_existing_file(object):
 '''该路径是文件'''
 def test(self, handler):
 return os.path.isfile(handler.full_path)
 def act(self, handler):
 handler.handle_file(handler.full_path)
class case_always_fail(object):
 '''所有情况都不符合时的默认处理类'''
 def test(self, handler):
 return True
 def act(self, handler):
 raise ServerException("Unknown object '{0}'".format(handler.path))

test方法用来判断是否符合该类指定的条件,act则是符合条件时的处理函数。其中的handler是对RequestHandler实例的引用,通过它,我们就能调用handle_file进行响应。

将原先的if-elif-else分支替换成遍历所有的条件类来看一下区别。

替换前:

def do_GET(self):
 try:
 # 文件完整路径
 full_path = os.getcwd() + self.path
 # 如果该路径不存在...
 if not os.path.exists(full_path):
 #抛出异常:文件未找到
 raise ServerException("'{0}' not found".format(self.path))
 # 如果该路径是一个文件
 elif os.path.isfile(full_path):
 #调用 handle_file 处理该文件
 self.handle_file(full_path)
 # 如果该路径不是一个文件
 else:
 #抛出异常:该路径为不知名对象
 raise ServerException("Unknown object '{0}'".format(self.path))
 # 处理异常
 except Exception as msg:
 self.handle_error(msg)

替换后:

# 所有可能的情况
Cases = [case_no_file(),
 case_existing_file(),
 case_always_fail()]
def do_GET(self):
 try:
 # 文件完整路径
 full_path = os.getcwd() + self.path
 #遍历所有可能的情况
 for case in self.Cases:
 #如果满足该类情况
 if case.test(self):
 #调用相应的act函数
 case.act(self)
 break
 # 处理异常
 except Exception as msg:
 self.handle_error(msg)

这样每当我们需要考虑一个新的情况时,只要新写一个条件处理类然后加到 Cases 中去就行了,是不是比原先在if-elif-else中添加条件的做法看起来更加干净更加清楚呢。

在编程中,我们一定要提高简洁性,减少代码冗杂。

展开阅读全文

页面更新:2024-03-13

标签:合时   简洁性   冗杂   遍历   篇文章   分支   路径   函数   异常   条件   完整   情况   简单   地址   服务器   文件   方法   体育

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top