python - 关于有效参数映射的问题
问题描述
下面的代码使我更容易使用 Pymongo。
但我正在尝试重构它,因为我认为它太低效了。
由于我是初学者,我尝试了几次,但我对它并不满意,所以我想请教一些建议。
对不起,代码很乱。参考一下,
如果有任何图书馆或简单的例子,请告诉我。谢谢!
def find_(self, collection, find_value=None, projection=None, sort=None, skip=None, limit=None, multi_array=None, cursor=False):
if sort is None:
if skip is None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection)
if skip is not None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).skip(skip)
if skip is None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).limit(limit)
if skip is not None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).skip(skip).limit(limit)
else:
arg = tuple((key, val) for key, val in sort.items())
if skip is None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg)
if skip is not None and limit is None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).skip(skip)
if skip is None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).limit(limit)
if skip is not None and limit is not None:
cursor_result = self.db_path[collection].find(find_value if projection is None else find_value, projection).sort(arg).skip(skip).limit(limit)
解决方案
您的代码几乎与将要获得的效率一样高,因为cursor_result
始终由一个完成所有实际工作的分支设置。唯一的问题是它有很多重复的代码。您可以通过一次处理每个选项来将其分解。
def find_(self, collection, find_value=None, projection=None, sort=None, skip=None, limit=None, multi_array=None, cursor=False):
# Get the right path and call find
cursor_result = self.db_path[collection].find(find_value, projection)
# Sort if necessary
if sort is not None:
cursor_result = cursor_result.sort(tuple(sort.items()))
# Skip if necessary
if skip is not None:
cursor_result = cursor_result.skip(skip)
# Limit if necessary
if limit is not None:
cursor_result = cursor_result.limit(limit)
推荐阅读
- reactjs - (原因:CORS 请求没有成功)
- pickle - 由于导入问题,Ray 无法取消远程功能?
- amazon-elastic-beanstalk - 如何在 aws beanstalk 文件 install_packages.config 中为 yum install 指定存储库?
- swift - 一次更改一个状态以查看清单
- php - Laravel Laravel\Socialite\Two\InvalidStateException
- python - 通过另一个 dict 订购 Django 查询集
- javascript - 如何在href中获取具有相同关键字的元素
- r - 如何在 R 中读取带有重复列的羽毛文件
- javascript - 如何在不下载图片的情况下将 p5 画布渲染到 Cloudinary
- c# - ASP.NET MVC 路由中的异常行为