Python 在django中构造url的最佳方法

Python 在django中构造url的最佳方法,python,django,python-3.x,Python,Django,Python 3.x,以下是我当前用于测试我的网站是在本地部署、在临时部署还是在生产中部署的代码: def get_base_url(request=None): BASE_URL = request.META.get('HTTP_HOST') if request else settings.STATIC_SITE_URL if not BASE_URL.startswith('http'): BASE_URL = 'http://' + BASE_URL # such as "lo

以下是我当前用于测试我的网站是在本地部署、在临时部署还是在生产中部署的代码:

def get_base_url(request=None):
    BASE_URL = request.META.get('HTTP_HOST') if request else settings.STATIC_SITE_URL
    if not BASE_URL.startswith('http'):
        BASE_URL = 'http://' + BASE_URL # such as "localhost:8000"
    return BASE_URL
要执行类似发送密码重置链接的操作,我会执行以下操作:

BASE_URL = get_base_url(request)
PATH = BASE_URL.rstrip('/') + reverse('logged_in')

有没有更干净的方法?我尝试了其他几种方法,但这似乎返回了最正确和一致的结果。

根据我在将许多Django应用程序部署到生产环境中的经验,最好的方法是将设置分为不同的模块。在
使用多个设置文件
一章中也有很好的介绍

settings/
    base.py
    local.py
    stage.py
    production.py
本地
阶段
生产
继承自
基础

例如
local.py

from .base import *

DEBUG = True

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name',
        'HOST': 'localhost',
    }
}

INSTALLED_APPS += ['debug_toolbar', ]

BASE_URL = 'http://localhost:8080/'
from .base import *

DEBUG = False

...

BASE_URL = 'https://example.com'
from .base import *

DEBUG = False

BASE_URL = 'https://stage.example.com'
例如
production.py

from .base import *

DEBUG = True

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name',
        'HOST': 'localhost',
    }
}

INSTALLED_APPS += ['debug_toolbar', ]

BASE_URL = 'http://localhost:8080/'
from .base import *

DEBUG = False

...

BASE_URL = 'https://example.com'
from .base import *

DEBUG = False

BASE_URL = 'https://stage.example.com'
例如
stage.py

from .base import *

DEBUG = True

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name',
        'HOST': 'localhost',
    }
}

INSTALLED_APPS += ['debug_toolbar', ]

BASE_URL = 'http://localhost:8080/'
from .base import *

DEBUG = False

...

BASE_URL = 'https://example.com'
from .base import *

DEBUG = False

BASE_URL = 'https://stage.example.com'
在此之后,您可以在每个设置文件中为每个特定环境设置
BASE\u URL
,并从
settings.BASE\u URL
访问您想要的任何位置

If将使您的生活更加轻松,并允许您根据环境动态地配置设置