在django中使用子域

Ива*_*вой 12 python django python-2.7

请告诉我是否有可能(如果是这样,如何)用于每个用户子域的页面.例如,现在我有一个表格的URL:http://hostname.com/user/1我需要http://username.hostname.com/

Mat*_*our 20

您有多种选择,具体取决于您想要的深度.

  1. 一种选择是在Web服务器级别处理路由.基本上,您将捕获URL的子域部分并将其重写到服务器中的其他位置.

    例如http://username1.local.host/signin,您的网络服务器将捕获并在内部路由到诸如的资源/username1/signin.最终用户将是子域名,但您的代码将处理网址部分,而不是更明智的发生了什么.

    您的urls.py将像任何正常请求一样处理此问题.

    url_pattern = [
       ...
       url(r'(?P<subdomain>[a-z]+)/sigin/$', 'view'),
    ]
    
    Run Code Online (Sandbox Code Playgroud)

    对于Nginx,您需要查看"子域到子目录重写".

    我个人会将此选项用于您在问题中说明的内容.虽然这种方法最初设置起来有点棘手(保持它直到它工作).从长远来看,维护和使用起来会容易得多.

  2. 另一种选择是使用诸如Django子域之类的包来处理django级别的子域(我过去使用过这个子域并发现它是我的首选选项(就处理django代码中的子域而言)).没有太多细节,nginx将捕获子域并将其全部路由到django.然后Django将处理中间件级别的子域.

就个人而言,我会使用选项1.选项2是您希望在不同域上使用不同的应用程序,例如:blog.local.host,support.local.host.

  • 只是一个小警告,选项一会要求您将子域作为参数输入到每个视图中,并可能导致未使用变量的pep8警告(这是副本试图避免的). (4认同)
  • [Django Subdomains](http://django-subdomains.readthedocs.org/en/latest/) 似乎已被放弃,但有一个积极开发的分支:[abe312/django-subdomains](https://github.com /abe312/django-subdomains),使用“pip install subdomains”安装它。 (2认同)

Den*_*nis 7

考虑使用django-hosts

来自文档:

# For example, if you own example.com but want to serve 
# specific content at api.example.com and beta.example.com, 
# add the following to a hosts.py file:

from django_hosts import patterns, host

host_patterns = patterns('path.to',
    host(r'api', 'api.urls', name='api'),
    host(r'beta', 'beta.urls', name='beta'),
)
Run Code Online (Sandbox Code Playgroud)