问题:Django:如何管理开发和生产设置?

我一直在开发一个基本的应用程序。现在在部署阶段,很明显,我需要本地设置和生产设置。

很高兴知道以下内容:

  • 如何最好地处理开发和生产设置。
  • 如何仅在开发环境中保留django-debug-toolbar之类的应用程序。
  • 开发和部署设置的其他任何技巧和最佳做法。

I have been developing a basic app. Now at the deployment stage it has become clear I have need for both a local settings and production settings.

It would be great to know the following:

  • How best to deal with development and production settings.
  • How to keep apps such as django-debug-toolbar only in a development environment.
  • Any other tips and best practices for development and deployment settings.

回答 0

DJANGO_SETTINGS_MODULE环境变量,其设置文件Django的控件将加载。

因此,您可以为各自的环境创建单独的配置文件(请注意,它们当然可以import *来自单独的“共享设置”文件),并用于DJANGO_SETTINGS_MODULE控制使用哪个文件。

这是如何做:

如Django文档中所述:

DJANGO_SETTINGS_MODULE的值应采用Python路径语法,例如mysite.settings。请注意,设置模块应位于Python导入搜索路径上。

所以,让我们假设你创建myapp/production_settings.pymyapp/test_settings.py在源存储库。

在这种情况下,您将分别设置DJANGO_SETTINGS_MODULE=myapp.production_settings使用前者和DJANGO_SETTINGS_MODULE=myapp.test_settings后者。


从现在开始,问题归结为设置DJANGO_SETTINGS_MODULE环境变量。

设置DJANGO_SETTINGS_MODULE使用脚本或shell

然后,您可以使用引导脚本或流程管理器来加载正确的设置(通过设置环境),或者仅在启动Django:之前从您的Shell中运行它export DJANGO_SETTINGS_MODULE=myapp.production_settings

请注意,您可以随时从Shell运行此导出-它不需要存在于您的.bashrc容器中。

DJANGO_SETTINGS_MODULE使用流程管理器进行设置

如果您不喜欢编写用于设置环境的引导脚本(并且有很好的理由!),我建议您使用流程管理器:


最后,请注意,您可以利用PYTHONPATH变量将设置存储在完全不同的位置(例如,在生产服务器上,将其存储在中/etc/)。这允许将配置与应用程序文件分开。您可能想要或不想要它,这取决于您的应用程序的结构。

The DJANGO_SETTINGS_MODULE environment variable controls which settings file Django will load.

You therefore create separate configuration files for your respective environments (note that they can of course both import * from a separate, “shared settings” file), and use DJANGO_SETTINGS_MODULE to control which one to use.

Here’s how:

As noted in the Django documentation:

The value of DJANGO_SETTINGS_MODULE should be in Python path syntax, e.g. mysite.settings. Note that the settings module should be on the Python import search path.

So, let’s assume you created myapp/production_settings.py and myapp/test_settings.py in your source repository.

In that case, you’d respectively set DJANGO_SETTINGS_MODULE=myapp.production_settings to use the former and DJANGO_SETTINGS_MODULE=myapp.test_settings to use the latter.


From here on out, the problem boils down to setting the DJANGO_SETTINGS_MODULE environment variable.

Setting DJANGO_SETTINGS_MODULE using a script or a shell

You can then use a bootstrap script or a process manager to load the correct settings (by setting the environment), or just run it from your shell before starting Django: export DJANGO_SETTINGS_MODULE=myapp.production_settings.

Note that you can run this export at any time from a shell — it does not need to live in your .bashrc or anything.

Setting DJANGO_SETTINGS_MODULE using a Process Manager

If you’re not fond of writing a bootstrap script that sets the environment (and there are very good reasons to feel that way!), I would recommend using a process manager:


Finally, note that you can take advantage of the PYTHONPATH variable to store the settings in a completely different location (e.g. on a production server, storing them in /etc/). This allows for separating configuration from application files. You may or may not want that, it depends on how your app is structured.


回答 1

默认情况下,使用生产设置,但settings_dev.py在与文件相同的文件夹中创建一个名为的settings.py文件。在此处添加替代,例如DEBUG=True

在将用于开发的计算机上,将此添加到您的~/.bashrc文件中:

export DJANGO_DEVELOPMENT=true

settings.py文件底部,添加以下内容。

# Override production variables if DJANGO_DEVELOPMENT env variable is set
if os.environ.get('DJANGO_DEVELOPMENT'):
    from settings_dev import *  # or specific overrides

(请注意,*通常应避免在Python 中导入)

默认情况下,生产服务器将不覆盖任何内容。做完了!

与其他答案相比,该答案更简单,因为它不需要更新PYTHONPATH或设置DJANGO_SETTINGS_MODULE,而每次只允许您处理一个django项目。

By default use production settings, but create a file called settings_dev.py in the same folder as your settings.py file. Add overrides there, such as DEBUG=True.

On the computer that will be used for development, add this to your ~/.bashrc file:

export DJANGO_DEVELOPMENT=true

At the bottom of your settings.py file, add the following.

# Override production variables if DJANGO_DEVELOPMENT env variable is set
if os.environ.get('DJANGO_DEVELOPMENT'):
    from settings_dev import *  # or specific overrides

(Note that importing * should generally be avoided in Python)

By default the production servers will not override anything. Done!

Compared to the other answers, this one is simpler because it doesn’t require updating PYTHONPATH, or setting DJANGO_SETTINGS_MODULE which only allows you to work on one django project at a time.


回答 2

通常每个环境有一个设置文件,还有一个共享设置文件:

/myproject/
  settings.production.py
  settings.development.py
  shared_settings.py

我的每个环境文件都有:

try:
    from shared_settings import *
except ImportError:
    pass

这使我可以在必要时覆盖共享设置(通过在该节下面添加修改)。

然后,通过将其链接到settings.py来选择要使用的设置文件:

ln -s settings.development.py settings.py

I usually have one settings file per environment, and a shared settings file:

/myproject/
  settings.production.py
  settings.development.py
  shared_settings.py

Each of my environment files has:

try:
    from shared_settings import *
except ImportError:
    pass

This allows me to override shared settings if necessary (by adding the modifications below that stanza).

I then select which settings files to use by linking it in to settings.py:

ln -s settings.development.py settings.py

回答 3

这是我通过6个简单步骤完成的操作:

  1. 在项目目录中创建一个文件夹,并将其命名settings

    项目结构:

    myproject/
           myapp1/
           myapp2/              
           myproject/
                  settings/
  2. 创建内部4个Python文件settings目录,即__init__.pybase.pydev.pyprod.py

    设置文件:

    settings/
         __init__.py
         base.py
         prod.py
         dev.py 
  3. 打开__init__.py并填写以下内容:

    初始化 .py:

    from .base import *
    # you need to set "myproject = 'prod'" as an environment variable
    # in your OS (on which your website is hosted)
    if os.environ['myproject'] == 'prod':
       from .prod import *
    else:
       from .dev import *
  4. 打开base.py并填写所有常用设置(将在生产和开发中使用)。例如:

    base.py:

    import os
    ...
    INSTALLED_APPS = [...]
    MIDDLEWARE = [...]
    TEMPLATES = [{...}]
    ...
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    MEDIA_ROOT = os.path.join(BASE_DIR, '/path/')
    MEDIA_URL = '/path/'
  5. 打开dev.py并包含特定于开发的内容,例如:

    dev.py:

    DEBUG = True
    ALLOWED_HOSTS = ['localhost']
    ...
  6. 打开prod.py并包含特定于生产的内容,例如:

    prod.py:

    DEBUG = False
    ALLOWED_HOSTS = ['www.example.com']
    LOGGING = [...]
    ...

This is how I do it in 6 easy steps:

  1. Create a folder inside your project directory and name it settings.

    Project structure:

    myproject/
           myapp1/
           myapp2/              
           myproject/
                  settings/
    
  2. Create four python files inside of the settings directory namely __init__.py, base.py, dev.py and prod.py

    Settings files:

    settings/
         __init__.py
         base.py
         prod.py
         dev.py 
    
  3. Open __init__.py and fill it with the following content:

    init.py:

    from .base import *
    # you need to set "myproject = 'prod'" as an environment variable
    # in your OS (on which your website is hosted)
    if os.environ['myproject'] == 'prod':
       from .prod import *
    else:
       from .dev import *
    
  4. Open base.py and fill it with all the common settings (that will be used in both production as well as development.) for example:

    base.py:

    import os
    ...
    INSTALLED_APPS = [...]
    MIDDLEWARE = [...]
    TEMPLATES = [{...}]
    ...
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    MEDIA_ROOT = os.path.join(BASE_DIR, '/path/')
    MEDIA_URL = '/path/'
    
  5. Open dev.py and include that stuff which is development specific for example:

    dev.py:

    DEBUG = True
    ALLOWED_HOSTS = ['localhost']
    ...
    
  6. Open prod.py and include that stuff which is production specific for example:

    prod.py:

    DEBUG = False
    ALLOWED_HOSTS = ['www.example.com']
    LOGGING = [...]
    ...
    

回答 4

创建多个settings*.py文件,推断出每个环境需要更改的变量。然后在主settings.py文件的末尾:

try:
  from settings_dev import *
except ImportError:
  pass

settings_*为每个阶段保留单独的文件。

settings_dev.py文件顶部,添加以下内容:

import sys
globals().update(vars(sys.modules['settings']))

导入需要修改的变量。

Wiki条目提供有关如何拆分设置的更多想法。

Create multiple settings*.py files, extrapolating the variables that need to change per environment. Then at the end of your master settings.py file:

try:
  from settings_dev import *
except ImportError:
  pass

You keep the separate settings_* files for each stage.

At the top of your settings_dev.py file, add this:

import sys
globals().update(vars(sys.modules['settings']))

To import variables that you need to modify.

This wiki entry has more ideas on how to split your settings.


回答 5

我使用了很棒的django-configuration,所有设置都存储在我的计算机中settings.py

from configurations import Configuration

class Base(Configuration):
    # all the base settings here...
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    ...

class Develop(Base):
    # development settings here...
    DEBUG = True 
    ...

class Production(Base):
    # production settings here...
    DEBUG = False

要配置Django项目,我只需遵循docs即可

I use the awesome django-configurations, and all the settings are stored in my settings.py:

from configurations import Configuration

class Base(Configuration):
    # all the base settings here...
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    ...

class Develop(Base):
    # development settings here...
    DEBUG = True 
    ...

class Production(Base):
    # production settings here...
    DEBUG = False

To configure the Django project I just followed the docs.


回答 6

这是我们使用的方法:

  • 一个settings将设置分成多个文件以增强可读性的模块;
  • 一个.env.json文件,用于存储我们要从git存储库中排除或特定于环境的凭据和参数;
  • 一个env.py文件来读取.env.json文件

考虑以下结构:

...
.env.json           # the file containing all specific credentials and parameters
.gitignore          # the .gitignore file to exclude `.env.json`
project_name/       # project dir (the one which django-admin.py creates)
  accounts/         # project's apps
    __init__.py
    ...
  ...
  env.py            # the file to load credentials
  settings/
    __init__.py     # main settings file
    database.py     # database conf
    storage.py      # storage conf
    ...
venv                # virtualenv
...

.env.json喜欢:

{
    "debug": false,
    "allowed_hosts": ["mydomain.com"],
    "django_secret_key": "my_very_long_secret_key",
    "db_password": "my_db_password",
    "db_name": "my_db_name",
    "db_user": "my_db_user",
    "db_host": "my_db_host",
}

project_name/env.py

<!-- language: lang-python -->
import json
import os


def get_credentials():
    env_file_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    with open(os.path.join(env_file_dir, '.env.json'), 'r') as f:
        creds = json.loads(f.read())
    return creds


credentials = get_credentials()

我们可以进行以下设置:

<!-- language: lang-py -->
# project_name/settings/__init__.py
from project_name.env import credentials
from project_name.settings.database import *
from project_name.settings.storage import *
...

SECRET_KEY = credentials.get('django_secret_key')

DEBUG = credentials.get('debug')

ALLOWED_HOSTS = credentials.get('allowed_hosts', [])

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    ...
]

if DEBUG:
    INSTALLED_APPS += ['debug_toolbar']

...

# project_name/settings/database.py
from project_name.env import credentials

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': credentials.get('db_name', ''),
        'USER': credentials.get('db_user', ''),
        'HOST': credentials.get('db_host', ''),
        'PASSWORD': credentials.get('db_password', ''),
        'PORT': '5432',
    }
}

该解决方案的好处是:

  • 用于本地开发的用户专用凭证和配置,而无需修改git存储库;
  • 针对特定环境的配置,例如,您可以具有三个不同的环境,其中具有三个不同的环境,.env.json例如dev,stagging和production;
  • 凭证不在存储库中

希望对您有所帮助,请告诉我您是否对此解决方案有所了解。

Here is the approach we use :

  • a settings module to split settings into multiple files for readability ;
  • a .env.json file to store credentials and parameters that we want excluded from our git repository, or that are environment specific ;
  • an env.py file to read the .env.json file

Considering the following structure :

...
.env.json           # the file containing all specific credentials and parameters
.gitignore          # the .gitignore file to exclude `.env.json`
project_name/       # project dir (the one which django-admin.py creates)
  accounts/         # project's apps
    __init__.py
    ...
  ...
  env.py            # the file to load credentials
  settings/
    __init__.py     # main settings file
    database.py     # database conf
    storage.py      # storage conf
    ...
venv                # virtualenv
...

With .env.json like :

{
    "debug": false,
    "allowed_hosts": ["mydomain.com"],
    "django_secret_key": "my_very_long_secret_key",
    "db_password": "my_db_password",
    "db_name": "my_db_name",
    "db_user": "my_db_user",
    "db_host": "my_db_host",
}

And project_name/env.py :

<!-- language: lang-python -->
import json
import os


def get_credentials():
    env_file_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    with open(os.path.join(env_file_dir, '.env.json'), 'r') as f:
        creds = json.loads(f.read())
    return creds


credentials = get_credentials()

We can have the following settings:

<!-- language: lang-py -->
# project_name/settings/__init__.py
from project_name.env import credentials
from project_name.settings.database import *
from project_name.settings.storage import *
...

SECRET_KEY = credentials.get('django_secret_key')

DEBUG = credentials.get('debug')

ALLOWED_HOSTS = credentials.get('allowed_hosts', [])

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    ...
]

if DEBUG:
    INSTALLED_APPS += ['debug_toolbar']

...

# project_name/settings/database.py
from project_name.env import credentials

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': credentials.get('db_name', ''),
        'USER': credentials.get('db_user', ''),
        'HOST': credentials.get('db_host', ''),
        'PASSWORD': credentials.get('db_password', ''),
        'PORT': '5432',
    }
}

the benefits of this solution are :

  • user specific credentials and configurations for local development without modifying the git repository ;
  • environment specific configuration, you can have for example three different environments with three different .env.json like dev, stagging and production ;
  • credentials are not in the repository

I hope this helps, just let me know if you see any caveats with this solution.


回答 7

我使用以下文件结构:

project/
   ...
   settings/
   settings/common.py
   settings/local.py
   settings/prod.py
   settings/__init__.py -> local.py

所以,__init__.py是(在Windows LN在UNIX或mklink)的链接,local.py或者可以是prod.py这样的配置仍然是在project.settings模块清洁和有组织的,如果你想使用一个特定的配置,你可以使用环境变量DJANGO_SETTINGS_MODULEproject.settings.prod,如果你需要在生产环境中运行命令。

在文件prod.pylocal.py

from .shared import *

DATABASE = {
    ...
}

并且该shared.py文件在没有特定配置的情况下保持全局状态。

I use the folloring file structure:

project/
   ...
   settings/
   settings/common.py
   settings/local.py
   settings/prod.py
   settings/__init__.py -> local.py

So __init__.py is a link (ln in unix or mklink in windows) to local.py or can be to prod.py so the configuration is still in the project.settings module is clean and organized, and if you want to use a particular config you can use the environment variable DJANGO_SETTINGS_MODULE to project.settings.prod if you need to run a command for production environment.

In the files prod.py and local.py:

from .shared import *

DATABASE = {
    ...
}

and the shared.py file keeps as global without specific configs.


回答 8

建立CS01的答案:

如果您在使用环境变量时遇到问题,请将其值设置为字符串(例如,我做了DJANGO_DEVELOPMENT="true")。

我还更改了cs01的文件工作流程,如下所示:

#settings.py
import os
if os.environ.get('DJANGO_DEVELOPMENT') is not None:
    from settings_dev import * 
else:
    from settings_production import *
#settings_dev.py
development settings go here
#settings_production.py
production settings go here

这样,Django无需在运行适当的设置文件之前通读整个设置文件。如果您的生产文件仅需要生产服务器上的内容,则此解决方案非常有用。

注意:在Python 3中,导入的文件需要.附加一个附件(例如from .settings_dev import *

building off cs01’s answer:

if you’re having problems with the environment variable, set its value to a string (e.g. I did DJANGO_DEVELOPMENT="true").

I also changed cs01’s file workflow as follows:

#settings.py
import os
if os.environ.get('DJANGO_DEVELOPMENT') is not None:
    from settings_dev import * 
else:
    from settings_production import *
#settings_dev.py
development settings go here
#settings_production.py
production settings go here

This way, Django doesn’t have to read through the entirety of a settings file before running the appropriate settings file. This solution comes in handy if your production file needs stuff that’s only on your production server.

Note: in Python 3, imported files need to have a . appended (e.g. from .settings_dev import *)


回答 9

如果要保留1个设置文件,并且您的开发操作系统与生产操作系统不同,则可以将其放在settings.py的底部:

from sys import platform
if platform == "linux" or platform == "linux2":
    # linux
    # some special setting here for when I'm on my prod server
elif platform == "darwin":
    # OS X
    # some special setting here for when I'm developing on my mac
elif platform == "win32":
    # Windows...
    # some special setting here for when I'm developing on my pc

阅读更多:如何检查Python中的操作系统?

If you want to keep 1 settings file, and your development operating system is different than your production operating system, you can put this at the bottom of your settings.py:

from sys import platform
if platform == "linux" or platform == "linux2":
    # linux
    # some special setting here for when I'm on my prod server
elif platform == "darwin":
    # OS X
    # some special setting here for when I'm developing on my mac
elif platform == "win32":
    # Windows...
    # some special setting here for when I'm developing on my pc

Read more: How do I check the operating system in Python?


回答 10

这似乎已经得到了回答,但是我将其与版本控制结合使用的方法如下:

在与我也添加到.gitignore的本地开发环境上的设置相同的目录中设置一个env.py文件:

env.py:

#!usr/bin/python

DJANGO_ENV = True
ALLOWED_HOSTS = ['127.0.0.1', 'dev.mywebsite.com']

.gitignore:

mywebsite/env.py

settings.py:

if os.path.exists(os.getcwd() + '/env.py'):
    #env.py is excluded using the .gitignore file - when moving to production we can automatically set debug mode to off:
    from env import *
else:
    DJANGO_ENV = False

DEBUG = DJANGO_ENV

我只是发现它有效并且更加优雅-使用env.py可以很容易地看到我们的本地环境变量,并且我们可以在没有多个settings.py文件或类似文件的情况下处理所有这些问题。这种方法允许使用各种我们不想在生产服务器上设置的局部环境变量。通过版本控制使用.gitignore,我们还保持所有内容无缝集成。

This seems to have been answered, however a method which I use as combined with version control is the following:

Setup a env.py file in the same directory as settings on my local development environment that I also add to .gitignore:

env.py:

#!usr/bin/python

DJANGO_ENV = True
ALLOWED_HOSTS = ['127.0.0.1', 'dev.mywebsite.com']

.gitignore:

mywebsite/env.py

settings.py:

if os.path.exists(os.getcwd() + '/env.py'):
    #env.py is excluded using the .gitignore file - when moving to production we can automatically set debug mode to off:
    from env import *
else:
    DJANGO_ENV = False

DEBUG = DJANGO_ENV

I just find this works and is far more elegant – with env.py it is easy to see our local environment variables and we can handle all of this without multiple settings.py files or the likes. This methods allows for all sorts of local environment variables to be used that we wouldn’t want set on our production server. Utilising the .gitignore via version control we are also keeping everything seamlessly integrated.


回答 11

使用settings.py进行生产。在同一目录中创建settings_dev.py替代。

# settings_dev.py

from .settings import * 

DEBUG = False

在开发机器上,使用以下命令运行Django应用:

DJANGO_SETTINGS_MODULE=<your_app_name>.settings_dev python3 manage.py runserver

在生产机器上运行,就好像您只是拥有settings.py而已。

优点

  1. settings.py (用于生产)完全不知道存在任何其他环境。
  2. 要查看prod和dev之间的区别,您只需查看一个位置- settings_dev.py。无需配置收集散落settings_prod.pysettings_dev.pysettings_shared.py
  3. 如果在解决生产问题后有人将设置添加到您的产品配置中,您可以放心,该设置也会出现在您的开发配置中(除非被显式覆盖)。因此,不同配置文件之间的差异将被最小化。

Use settings.py for production. In the same directory create settings_dev.py for overrides.

# settings_dev.py

from .settings import * 

DEBUG = False

On a dev machine run your Django app with:

DJANGO_SETTINGS_MODULE=<your_app_name>.settings_dev python3 manage.py runserver

On a prod machine run as if you just had settings.py and nothing else.

ADVANTAGES

  1. settings.py (used for production) is completely agnostic to the fact that any other environments even exist.
  2. To see the difference between prod and dev you just look into a single location – settings_dev.py. No need to gather configurations scattered across settings_prod.py, settings_dev.py and settings_shared.py.
  3. If someone adds a setting to your prod config after troubleshooting a production issue you can rest assured that it will appear in your dev config as well (unless explicitly overridden). Thus the divergence between different config files will be minimized.

回答 12

对于设置文件的问题,我选择复制

Project
   |---__init__.py   [ write code to copy setting file from subdir to current dir]
   |---settings.py  (do not commit this file to git)
   |---setting1_dir
   |         |--  settings.py
   |---setting2_dir
   |         |--  settings.py

当您运行django时,将运行__init__py。这时,settings.py in setting1_dir将更换settings.py in Project

如何选择不同的环境?

  • __init__.py直接修改。
  • 制作一个bash文件进行修改__init__.py
  • 在linux中修改env,然后__init__.py读取此变量。

为什么要用这种方式?

因为我不喜欢同一目录中的太多文件,所以太多的文件会使其他合作伙伴感到困惑,并且对于IDE来说不是很好(IDE无法找到我们使用的文件)

如果您不想看到所有这些详细信息,可以将项目分为两部分。

  1. 制作像Spring Initializr这样的小工具,仅用于设置您的项目。(像复制文件一样)
  2. 您的项目代码

For the problem of setting files, I choose to copy

Project
   |---__init__.py   [ write code to copy setting file from subdir to current dir]
   |---settings.py  (do not commit this file to git)
   |---setting1_dir
   |         |--  settings.py
   |---setting2_dir
   |         |--  settings.py

When you run django, __init__py will be ran. At this time , settings.py in setting1_dir will replace settings.py in Project.

How to choose different env?

  • modify __init__.py directly.
  • make a bash file to modify __init__.py.
  • modify env in linux, and then let __init__.py read this variable.

Why use to this way?

Because I don’t like so many files in the same directory, too many files will confuse other partners and not very well for IDE.(IDE cannot find what file we use)

If you do not want to see all these details, you can divide project into two part.

  1. make your small tool like Spring Initializr, just for setup your project.(do sth like copy file)
  2. your project code

回答 13

我正在使用不同的app.yaml文件来更改Google Cloud App Engine中环境之间的配置。

您可以使用此命令在终端命令中创建代理连接:

./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:1433

https://cloud.google.com/sql/docs/sqlserver/connect-admin-proxy#macos-64-bit

档案:app.yaml

# [START django_app]
service: development
runtime: python37

env_variables:
  DJANGO_DB_HOST: '/cloudsql/myproject:myregion:myinstance'
  DJANGO_DEBUG: True

handlers:
# This configures Google App Engine to serve the files in the app's static
# directory.
- url: /static
  static_dir: static/

# This handler routes all requests not caught above to your main app. It is
# required when static routes are defined, but can be omitted (along with
# the entire handlers section) when there are no static files defined.
- url: /.*
  script: auto
# [END django_app]

I’m using different app.yaml file to change configuration between environments in google cloud app engine.

You can use this to create a proxy connection in your terminal command:

./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:1433

https://cloud.google.com/sql/docs/sqlserver/connect-admin-proxy#macos-64-bit

File: app.yaml

# [START django_app]
service: development
runtime: python37

env_variables:
  DJANGO_DB_HOST: '/cloudsql/myproject:myregion:myinstance'
  DJANGO_DEBUG: True

handlers:
# This configures Google App Engine to serve the files in the app's static
# directory.
- url: /static
  static_dir: static/

# This handler routes all requests not caught above to your main app. It is
# required when static routes are defined, but can be omitted (along with
# the entire handlers section) when there are no static files defined.
- url: /.*
  script: auto
# [END django_app]

回答 14

这是我的解决方案,具有不同的开发,测试和生产环境

import socket

[...]

DEV_PC = 'PC059'
host_name = socket.gethostname()

if host_name == DEV_PC:
   #do something
   pass
elif [...]

This is my solution, with different environements for dev, test and prod

import socket

[...]

DEV_PC = 'PC059'
host_name = socket.gethostname()

if host_name == DEV_PC:
   #do something
   pass
elif [...]

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。