简体   繁体   English

在Django中构造URL的最佳方法

[英]Best way to construct a url in django

Here is the code I'm currently using to test whether my website is deployed locally, on staging, or production: 这是我目前用来测试我的网站是在本地部署,在登台还是在生产中的代码:

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

And to do something like send a link for a password reset, I would do: 并执行类似发送密码重置链接的操作,我将这样做:

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

Is there a cleaner way to do this? 有没有更清洁的方法可以做到这一点? I tried a few others ways but this seems to return the most correct and consistent result. 我尝试了其他几种方法,但这似乎返回了最正确和一致的结果。

From my experience in deploying many Django apps to production, the best approach would be to separate settings into different modules. 根据我在将许多Django应用程序部署到生产中的经验,最好的方法是将设置分成不同的模块。 It is also very good described in Two Scoops of Django in Using Multiple Settings Files chapter. 在“ Using Multiple Settings Files一章中的“ Django的两个消息”中对此进行了很好的描述。

settings/
    base.py
    local.py
    stage.py
    production.py

local , stage , production inherit from base . localstageproductionbase继承。

For example local.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/'

For example production.py : 例如production.py

from .base import *

DEBUG = False

...

BASE_URL = 'https://example.com'

For example stage.py : 例如stage.py

from .base import *

DEBUG = False

BASE_URL = 'https://stage.example.com'

After this you can just set BASE_URL for each specific environment in each settings file and access in from settings.BASE_URL everywhere you want. 之后,您可以在每个设置文件中为每个特定的环境设置BASE_URL ,并在所需的任何位置从settings.BASE_URL访问。

If will make your life much easier and allow to configure you settings depending on environment very dynamically. 如果这样做将使您的生活更加轻松,并可以非常动态地根据环境配置您的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM