我正在尝试将这个PHP代码转换成Python。它只是返回树层次结构中的选项。在
function getAllSectors(&$output = null, $parent_id = 0, $indent = null){
$statement = $this->connect()->prepare("SELECT id, name FROM sectors WHERE parent_id =:parent_id ORDER BY parent_id, sort_order");
$statement->execute(array(
'parent_id' => $parent_id
));
// show the sectors one by one
while($row = $statement->fetch()){
$output .= '<option value=' . $row['id'] . '>' . $indent . $row['name'] . "</option>";
if($row['id'] != $parent_id){
// In case the current sectors's id is different than $parent_id
// I call the function again with new parameters(so it is recursive)
$this->getAllSectors($output, $row['id'], $indent . " ");
}
}
// return the list of sectors(call out is in index.php)
return $output;
}
我在Python中尝试过:
^{pr2}$我在用Python,SQLAlchemy,Tornado,主干。在
但是我不知道如何通过引用传递output
参数。我认为Python版本有无限循环,对吗?谁能给我提些建议吗?在
PHP代码的正确翻译是:
不需要将
output
传入递归调用,只需收集输出并将其添加到正在生成的当前输出中。我使用了一个列表来避免重复的字符串连接(这将为您提供二次性能,而不是线性的)。在您还缺少
ORDER BY
子句;当您同时对父id进行筛选时,不需要按parent_id
排序(它们都将是相同的),因此只需要对sort_order
列进行排序。在我假设这是SQLAlchemy;您可以使用
~
来声明WHERE NOT <column>
子句。在您还应该考虑将表示与作为树检索类别分开。然后,您可以使用生成器方法,避免将整个树保存在内存中的内存占用(尽管SQLAlchemy无论如何都会缓存大部分内容):
^{pr2}$然后使用模板引擎递归地呈现
children
元素。在对于演示,首先让我们在内存数据库中构建一些类别;这将使用模型的简化版本;树如下所示:
设置代码:
然后使用一个伪类将类方法绑定到,可以生成输出:
相关问题 更多 >
编程相关推荐