如何让 Django 根据“Host”确定要使用哪个 Site 对象? HTTP 请求中的标头?
考虑一个 Django 应用程序,它使用标准 Django sites
框架来为内容略有不同的多个站点提供服务。
托管它的传统方法是配置多个 Site
对象,并在多个 Django 项目中设置应用程序,每个项目在各自的 设置中指向不同的
SITE_ID
.py:s。
由于各种原因,我希望避免为每个新站点创建一个新项目。我希望能够设置一个项目,并让 Django 根据传入 HTTP 请求中引用的主机名确定要使用哪个 Site
对象。
实现此功能的推荐方法是什么?
澄清:我希望站点框架忽略settings.SITE_ID
(在settings.py
中硬编码)并动态获取Site对象基于 Host
标头中的内容。为什么有这个要求?我每小时会多次添加和删除站点,站点总数将超过 10,000 个,因此为每个站点设置一个 Django 项目并不是一种选择。这是 Django 可以解决的问题吗?如果是这样,实现这一目标的最佳方法是什么?
Consider a Django app built to serve multiple sites with slightly differing content using the standard Django sites
framework.
The traditional way to host this would be to configure multiple Site
objects and setup the app in multiple Django projects with each project pointing to a different SITE_ID
in their respective settings.py
:s.
For various reasons I'd like to avoid having to create a new project for each new site. I want to be able to setup one project and have Django figure out which Site
object to use based on the hostname referenced in the incoming HTTP request.
What is the recommended way to achieve this functionality?
Clarification: I want the site framework to ignore settings.SITE_ID
(which is hard-coded in settings.py
) and instead dynamically fetch Site objects based on what is in the Host
header. Why this requirement? I'll be adding and removing sites multiple times per hour and the total amount of sites will exceed 10,000, so setting up a Django project for each site is not an option. Is this a problem that is solvable in Django? If so, what is the best way to achieve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
推荐的方法是根本不要尝试它,因为设置不应在运行时更改。相反,在虚拟主机配置中设置一个变量,并让 WSGI 适配器脚本或
settings
模块根据该变量选择一个站点。The recommended way is to not attempt it at all, since settings should never change at runtime. Instead, set a variable in your virtual host configuration and have the WSGI adapter script or
settings
module pick one of the sites based on that.