Python 使用Django、水平和垂直分区辅助方法进行缩放,请解释
垂直分区辅助程序:Python 使用Django、水平和垂直分区辅助方法进行缩放,请解释,python,django,Python,Django,垂直分区辅助程序: class ApplicationRouter(object) def db_for_read(self, model, **hints): instance = hints.get('instance') if not instance: return None app_label = instance._meta.app_label return get_applic
class ApplicationRouter(object)
def db_for_read(self, model, **hints):
instance = hints.get('instance')
if not instance:
return None
app_label = instance._meta.app_label
return get_application_alias(app_label)
有人能解释一下这是怎么回事吗
现在这是水平分区:
class ForumPartitionRouter(object):
def db_for_read(self, model, **hints):
instance = hints.get('instance')
if not instance:
return None
forum_id = getattr(instance, 'forum_id', None)
if not forum_id:
return None
return get_forum_alias(forum_id)
我有点理解它们在做什么,但不确定其中一些行是什么样子的:
instance = hints.get('instance')
他正在讨论Disqs如何利用Django 1.2及更高版本中使用的数据库路由技术,该技术允许您同时连接到多个活动数据库。 与Django的早期版本不同,Django 1.2及更高版本使用字典字典,初始字典的键是授权数据库的标记,内部字典的键映射到旧版本中熟悉的Django设置 ForumPartitionRouter更明显:不同的论坛存储在不同的数据库中(这很有趣,因为很明显,他们有一些很棒的管理工具,允许他们在启动django服务器时将这些分区定义到django服务器,将每个django实例视为其系统的临时对象)服务器使用forum_id查找正确的数据库,从中获取论坛的相关成员(在本例中为帖子)。db_for_read()返回指向数据库的令牌 许多论坛都有许多帖子,但每个帖子都有一个论坛。因为论坛之间没有相互关系,所以您可以将每个论坛及其帖子存储在一个数据库中,完全独立于其他论坛及其帖子 如果你看第23页的例子,从他的例子中可以清楚地看出:
forum.post_set.all()
…发生的事情是论坛的对象id被用作某个表中的查找,该表将论坛id与网络上任何其他位置的数据库(不是表,而是数据库)关联
因此,在我看来,ApplicationRouter在关系方面也做了类似的事情。请看下面的文字:“垂直分区涉及创建列数较少的表,并使用其他表存储其余的列。”ApplicationRouter就是这样做的:当您使用一个应用程序,并且要访问不同表中的相关对象时,ApplicationRouter会查看请求和要填写的实例,并使用类似于ForumPartitionRouter的查找表返回数据库的键,在该数据库中可以查看相关实例的详细信息找到了
您可以在此处查找多个数据库:
Elf,谢谢。那么您认为这些调用“applicationRouter”或“forumpartitionrouter”是在幕后完成的,还是由开发人员显式调用的?它们就像上下文处理器。您编写一个路由器类,然后在settings.py中将其添加到数据库路由器中。当ORM执行查找时,它会循环通过任何开发人员提供的数据database_路由器,提供模型和任何可用实例,直到它得到除“无”之外的其他内容;这反过来提供了到所需数据库的连接的引用。在django/db/models/fields/related.py中,搜索“db_for_read”,您可以看到神奇之处。