基于 IP 或主机名的 Django 设置

发布于 2024-10-02 14:41:37 字数 167 浏览 1 评论 0原文

我想在我的设置中添加一些内容,例如

if ip in DEV_IPS:
   SOMESETTING = 'foo'
else:
   SOMESETTING = 'bar'

是否有一种简单的方法来获取 IP 或主机名 - 还有 - 这是一个坏主意吗?

I'd like to have something in my settings like

if ip in DEV_IPS:
   SOMESETTING = 'foo'
else:
   SOMESETTING = 'bar'

Is there an easy way to get the ip or hostname - also - is this is a bad idea ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彼岸花似海 2024-10-09 14:41:38
import socket
socket.gethostbyname(socket.gethostname())

但是,我建议不要这样做,而是为您正在使用的每个环境维护多个设置文件。

settings/__init__.py
settings/qa.py 
settings/production.py

__init__.py 具有所有默认值。在 qa.py 和任何其他设置文件的顶部,第一行包含:

from settings import *

后跟该特定环境所需的任何覆盖。

import socket
socket.gethostbyname(socket.gethostname())

However, I'd recommend against this and instead maintain multiple settings file for each environment you're working with.

settings/__init__.py
settings/qa.py 
settings/production.py

__init__.py has all of your defaults. At the top of qa.py, and any other settings file, the first line has:

from settings import *

followed by any overrides needed for that particular environment.

等风来 2024-10-09 14:41:38

一些商店使用的一种方法是在每台计算机上设置环境变量。或许可以称之为“环境”。在 POSIX 系统中,您可以在用户的​​ .profile 文件中执行类似 ENVIRONMENT=product 的操作(对于每个 shell 和操作系统,这会略有不同)。然后在 settings.py 中你可以执行如下操作:

import os

if os.environ['ENVIRONMENT'] == 'production':
    # Production
    DATABASE_ENGINE = 'mysql'
    DATABASE_NAME = ....
else:
    # Development

One method some shops use is to have an environment variable set on each machine. Maybe called "environment". In POSIX systems you can do something like ENVIRONMENT=production in the user's .profile file (this will be slightly different for each shell and OS). Then in settings.py you can do something like this:

import os

if os.environ['ENVIRONMENT'] == 'production':
    # Production
    DATABASE_ENGINE = 'mysql'
    DATABASE_NAME = ....
else:
    # Development
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文