标签归档:settings

Django:配置不正确:SECRET_KEY设置不得为空

问题:Django:配置不正确:SECRET_KEY设置不得为空

我正在尝试设置包括某些基本设置的多个设置文件(开发,生产等)。虽然无法成功。当我尝试运行./manage.py runserver时,出现以下错误:

(cb)clime@den /srv/www/cb $ ./manage.py runserver
ImproperlyConfigured: The SECRET_KEY setting must not be empty.

这是我的设置模块:

(cb)clime@den /srv/www/cb/cb/settings $ ll
total 24
-rw-rw-r--. 1 clime clime 8230 Oct  2 02:56 base.py
-rw-rw-r--. 1 clime clime  489 Oct  2 03:09 development.py
-rw-rw-r--. 1 clime clime   24 Oct  2 02:34 __init__.py
-rw-rw-r--. 1 clime clime  471 Oct  2 02:51 production.py

基本设置(包含SECRET_KEY):

(cb)clime@den /srv/www/cb/cb/settings $ cat base.py:
# Django base settings for cb project.

import django.conf.global_settings as defaults

DEBUG = False
TEMPLATE_DEBUG = False

INTERNAL_IPS = ('127.0.0.1',)

ADMINS = (
    ('clime', 'clime7@gmail.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        #'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'cwu',                   # Or path to database file if using sqlite3.
        'USER': 'clime',                 # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Prague'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = False # TODO: make this true and accustom date time input

DATE_INPUT_FORMATS = defaults.DATE_INPUT_FORMATS + ('%d %b %y', '%d %b, %y') # + ('25 Oct 13', '25 Oct, 13')

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/srv/www/cb/media'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/srv/www/cb/static'

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&022shmi1jcgihb*'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.request',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'web.context.inbox',
    'web.context.base',
    'web.context.main_search',
    'web.context.enums',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'watson.middleware.SearchContextMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'middleware.UserMemberMiddleware',
    'middleware.ProfilerMiddleware',
    'middleware.VaryOnAcceptMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'cb.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cb.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/srv/www/cb/web/templates',
    '/srv/www/cb/templates',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'south',
    'grappelli', # must be before admin
    'django.contrib.admin',
    'django.contrib.admindocs',
    'endless_pagination',
    'debug_toolbar',
    'djangoratings',
    'watson',
    'web',
)

AUTH_USER_MODEL = 'web.User'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': "/srv/www/cb/logs/application.log",
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'web': {
            'handlers': ['console', 'logfile'],
            'level': 'DEBUG',
        },
    },
}

LOGIN_URL = 'login'
LOGOUT_URL = 'logout'

#ENDLESS_PAGINATION_LOADING = """
#    <img src="/static/web/img/preloader.gif" alt="loading" style="margin:auto"/>
#"""
ENDLESS_PAGINATION_LOADING = """
    <div class="spinner small" style="margin:auto">
        <div class="block_1 spinner_block small"></div>
        <div class="block_2 spinner_block small"></div>
        <div class="block_3 spinner_block small"></div>
    </div>
"""

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False,
}

import django.template.loader
django.template.loader.add_to_builtins('web.templatetags.cb_tags')
django.template.loader.add_to_builtins('web.templatetags.tag_library')

WATSON_POSTGRESQL_SEARCH_CONFIG = 'public.english_nostop'

设置文件之一:

(cb)clime@den /srv/www/cb/cb/settings $ cat development.py 
from base import *

DEBUG = True
TEMPLATE_DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', '31.31.78.149']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'cwu',
        'USER': 'clime',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

MEDIA_ROOT = '/srv/www/cb/media/'

STATIC_ROOT = '/srv/www/cb/static/'

TEMPLATE_DIRS = (
    '/srv/www/cb/web/templates',
    '/srv/www/cb/templates',
)

代码在manage.py

(cb)clime@den /srv/www/cb $ cat manage.py 
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cb.settings.development")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

如果添加from base import */srv/www/cb/cb/settings/__init__.py(否则为空),它会神奇地开始工作,但我不明白为什么。任何人都可以向我解释这是怎么回事?它一定是一些python模块魔术。

编辑:如果我从base.py中删除此行,一切也将开始工作

django.template.loader.add_to_builtins('web.templatetags.cb_tags')

如果我从web.templatetags.cb_tags中删除此行,它也将开始工作:

from endless_pagination.templatetags import endless

我想这是因为最终导致

from django.conf import settings
PER_PAGE = getattr(settings, 'ENDLESS_PAGINATION_PER_PAGE', 10)

因此,它会产生一些怪异的循环内容并结束游戏。

I am trying to set up multiple setting files (development, production, ..) that include some base settings. Cannot succeed though. When I try to run ./manage.py runserver I am getting the following error:

(cb)clime@den /srv/www/cb $ ./manage.py runserver
ImproperlyConfigured: The SECRET_KEY setting must not be empty.

Here is my settings module:

(cb)clime@den /srv/www/cb/cb/settings $ ll
total 24
-rw-rw-r--. 1 clime clime 8230 Oct  2 02:56 base.py
-rw-rw-r--. 1 clime clime  489 Oct  2 03:09 development.py
-rw-rw-r--. 1 clime clime   24 Oct  2 02:34 __init__.py
-rw-rw-r--. 1 clime clime  471 Oct  2 02:51 production.py

Base settings (contain SECRET_KEY):

(cb)clime@den /srv/www/cb/cb/settings $ cat base.py:
# Django base settings for cb project.

import django.conf.global_settings as defaults

DEBUG = False
TEMPLATE_DEBUG = False

INTERNAL_IPS = ('127.0.0.1',)

ADMINS = (
    ('clime', 'clime7@gmail.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        #'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'cwu',                   # Or path to database file if using sqlite3.
        'USER': 'clime',                 # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Prague'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = False # TODO: make this true and accustom date time input

DATE_INPUT_FORMATS = defaults.DATE_INPUT_FORMATS + ('%d %b %y', '%d %b, %y') # + ('25 Oct 13', '25 Oct, 13')

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/srv/www/cb/media'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/srv/www/cb/static'

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.request',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'web.context.inbox',
    'web.context.base',
    'web.context.main_search',
    'web.context.enums',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'watson.middleware.SearchContextMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'middleware.UserMemberMiddleware',
    'middleware.ProfilerMiddleware',
    'middleware.VaryOnAcceptMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'cb.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cb.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/srv/www/cb/web/templates',
    '/srv/www/cb/templates',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'south',
    'grappelli', # must be before admin
    'django.contrib.admin',
    'django.contrib.admindocs',
    'endless_pagination',
    'debug_toolbar',
    'djangoratings',
    'watson',
    'web',
)

AUTH_USER_MODEL = 'web.User'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': "/srv/www/cb/logs/application.log",
            'maxBytes': 50000,
            'backupCount': 2,
            'formatter': 'standard',
        },
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'standard'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django': {
            'handlers':['console'],
            'propagate': True,
            'level':'WARN',
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'web': {
            'handlers': ['console', 'logfile'],
            'level': 'DEBUG',
        },
    },
}

LOGIN_URL = 'login'
LOGOUT_URL = 'logout'

#ENDLESS_PAGINATION_LOADING = """
#    <img src="/static/web/img/preloader.gif" alt="loading" style="margin:auto"/>
#"""
ENDLESS_PAGINATION_LOADING = """
    <div class="spinner small" style="margin:auto">
        <div class="block_1 spinner_block small"></div>
        <div class="block_2 spinner_block small"></div>
        <div class="block_3 spinner_block small"></div>
    </div>
"""

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False,
}

import django.template.loader
django.template.loader.add_to_builtins('web.templatetags.cb_tags')
django.template.loader.add_to_builtins('web.templatetags.tag_library')

WATSON_POSTGRESQL_SEARCH_CONFIG = 'public.english_nostop'

One of the setting files:

(cb)clime@den /srv/www/cb/cb/settings $ cat development.py 
from base import *

DEBUG = True
TEMPLATE_DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', '31.31.78.149']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'cwu',
        'USER': 'clime',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

MEDIA_ROOT = '/srv/www/cb/media/'

STATIC_ROOT = '/srv/www/cb/static/'

TEMPLATE_DIRS = (
    '/srv/www/cb/web/templates',
    '/srv/www/cb/templates',
)

Code in manage.py:

(cb)clime@den /srv/www/cb $ cat manage.py 
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cb.settings.development")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

If I add from base import * into /srv/www/cb/cb/settings/__init__.py (which is otherwise empty), it magically starts to work but I don’t understand why. Anyone could explain to me what’s going on here? It must be some python module magic.

EDIT: Everything also starts to work if I remove this line from base.py

django.template.loader.add_to_builtins('web.templatetags.cb_tags')

If I remove this line from web.templatetags.cb_tags, it also starts to work:

from endless_pagination.templatetags import endless

I guess it is because, in the end, it leads to

from django.conf import settings
PER_PAGE = getattr(settings, 'ENDLESS_PAGINATION_PER_PAGE', 10)

So it creates some weird circular stuff and game over.


回答 0

我有同样的错误,结果是设置或设置模块本身加载的模块或类之间存在循环依赖关系。在我的情况下,这是一个中间件类,该类在设置中被命名,该类本身试图加载设置。

I had the same error and it turned out to be a circular dependency between a module or class loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.


回答 1

在按照Daniel Greenfield的《Django两个独家报道》一书中的说明重组设置后,我遇到了同样的问题。

我通过设置解决了该问题

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local")

manage.pywsgi.py

更新:

在上述解决方案中,local是我的settings文件夹中的文件名(settings / local.py),其中包含我的本地环境的设置。

解决此问题的另一种方法是将所有常用设置保留在settings / base.py中,然后为生产,登台和开发环境创建3个单独的设置文件。

您的设置文件夹如下所示:

settings/
    __init__.py
    base.py
    local.py
    prod.py
    stage.py

并将以下代码保存在 settings/__init__.py

from .base import *

env_name = os.getenv('ENV_NAME', 'local')

if env_name == 'prod':
    from .prod import *
elif env_name == 'stage':
    from .stage import *
else:
    from .local import *

I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield’s book Two scoops of Django.

I resolved the issue by setting

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local")

in manage.py and wsgi.py.

Update:

In the above solution, local is the file name (settings/local.py) inside my settings folder, which holds the settings for my local environment.

Another way to resolve this issue is to keep all your common settings inside settings/base.py and then create 3 separate settings files for your production, staging and dev environments.

Your settings folder will look like:

settings/
    __init__.py
    base.py
    local.py
    prod.py
    stage.py

and keep the following code in your settings/__init__.py

from .base import *

env_name = os.getenv('ENV_NAME', 'local')

if env_name == 'prod':
    from .prod import *
elif env_name == 'stage':
    from .stage import *
else:
    from .local import *

回答 2

我有同样的错误 python manage.py runserver

对我来说,这是由于过时的已编译二进制(.pyc)文件所致。删除项目中的所有此类文件后,服​​务器再次开始运行。:)

因此,如果您无所事事地收到此错误,即不进行与Django设置有关的任何更改,那么这可能是个不错的选择。

I had the same error with python manage.py runserver.

For me, it turned out that it was because of a stale compiled binary (.pyc) file. After deleting all such files in my project, server started running again. :)

So if you get this error, out of nowhere, i.e without making any change seemingly-related to django-settings, this could be a good first measure.


回答 3

删除.pyc文件

Ubuntu终端命令用于删除.pyc: find . -name "*.pyc" -exec rm -rf {} \;

我在执行python manage.py runserver时遇到了相同的错误。这是因为.pyc文件。我从项目目录中删除了.pyc文件,然后它开始工作了。

Remove .pyc files

Ubuntu terminal command for deleting .pyc : find . -name "*.pyc" -exec rm -rf {} \;

I have got same error when I did python manage.py runserver. It was because .pyc file. I deleted .pyc file from project directory then it was working.


回答 4

我没有指定设置文件:

python manage.py runserver --settings=my_project.settings.develop

I hadn’t specified the settings file:

python manage.py runserver --settings=my_project.settings.develop

回答 5

它开始工作是因为在base.py上,您具有基本设置文件中所需的所有信息。您需要以下行:

SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*'

因此它可以正常工作,并且在您执行操作时from base import *,会将SECRET_KEY导入到您的development.py

在执行任何自定义设置之前,您应该始终导入基本设置。


编辑:另外,当django从程序包中导入开发时,由于您from base import *在内部定义,因此它将初始化base 内部的所有变量__init__.py

It starts working because on the base.py you have all information needed in a basic settings file. You need the line:

SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*'

So it works and when you do from base import *, it imports SECRET_KEY into your development.py.

You should always import basic settings before doing any custom settings.


EDIT: Also, when django imports development from your package, it initializes all variables inside base since you defined from base import * inside __init__.py


回答 6

我认为这是环境错误,您应该尝试设置:DJANGO_SETTINGS_MODULE='correctly_settings'

I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'


回答 7

我在Celery上也遇到了同样的问题。我的setting.py 之前

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

后:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)

如果未定义环境变量,则:SECRET_KEY = 您的开发密钥

I had the same problem with Celery. My setting.py before:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

after:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)

If the environment variables are not defined then: SECRET_KEY = YOUR developing key


回答 8

在设置目录的init .py中,输入正确的导入,例如:

from Project.settings.base import *

无需更改wsgi.py或manage.py

In the init.py of the settings directory write the correct import, like:

from Project.settings.base import *

No need to change wsgi.py or manage.py


回答 9

我通过停用所有激活到virtualenv的活动会话并再次启动它,解决了在OS X上使用Django 1.5和1.6的OS X上出现的问题。

I solved this problem occurring on OS X with Django both 1.5 and 1.6 by deactivating all active sessions to virtualenv and starting it again.


回答 10

为了将另一个潜在的解决方案添加到组合中,我有一个settings文件夹以及一个settings.py在项目目录中。(我正在从基于环境的设置文件切换回一个文件。此后我一直在考虑。)

Python对我要导入project/settings.py还是感到困惑project/settings/__init__.py。我删除了settings目录,现在一切正常。

To throw another potential solution into the mix, I had a settings folder as well as a settings.py in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)

Python was getting confused about whether I wanted to import project/settings.py or project/settings/__init__.py. I removed the settings dir and everything now works fine.


回答 11

对于使用PyCharm的任何人:绿色的“运行选定的配置”按钮将产生此错误,但运行以下工作:

py manage.py runserver 127.0.0.1:8000 --settings=app_name.settings.development

要解决此问题,您需要编辑配置的环境变量。为此,请单击绿色运行按钮左侧的“选择运行/调试配置”下拉菜单,然后单击“编辑配置”。在“环境”标签下,将环境变量更改DJANGO_SETTINGS_MODULEapp_name.settings.development

For anyone using PyCharm: the green “Run selected configuration” button would produce this error, yet running the following works:

py manage.py runserver 127.0.0.1:8000 --settings=app_name.settings.development

To fix this you need to edit the configuration’s environment variables. To do this click the “Select run/debug configuration” drop-down menu to the left of the green run button and then click on “edit configuration”. Under the “environment” tab change the environment variable DJANGO_SETTINGS_MODULE to app_name.settings.development.


回答 12

我只是想补充一点,当我的数据库名称在settings.py文件中拼写错误时出现了此错误,因此无法创建数据库。

I just wanted to add that I got this error when my database name was spelled wrong in my settings.py file so the DB couldn’t be created.


回答 13

我通过修复有错字的TEMPLATES设置在1.8.4上解决了此问题(删除TEMPLATES [‘debug’]解决了此问题)

翻阅您最近更改的设置,确保所有键都是按书进行的。

I solved this problem on 1.8.4 by fixing the TEMPLATES settings which had a typo (removing TEMPLATES[‘debug’] solved it)

Go over the settings that you have changed recently, make sure all keys are by-the-book.


回答 14

我通过删除文件中等号(=)周围的空格解决了这个问题.env

I solved this problem by removing the spaces around equal signs (=) in my .env file.


回答 15

在我的情况下,问题是-我有我的app_folder,并settings.py在里面。然后我决定进入Settings folder内部app_folder-并与之发生冲突settings.py。只是重命名了Settings folder-一切正常。

In my case the problem was – I had my app_folder and settings.py in it. Then I decided to make Settings folder inside app_folder – and that made a collision with settings.py. Just renamed that Settings folder – and everything worked.


回答 16

我的Mac OS不喜欢它没有在设置文件中找到env变量集:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')

但是将env var添加到本地Mac OS开发环境后,该错误消失了:

export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'

就我而言,我还需要添加--settings参数:

python3 manage.py check --deploy --settings myappname.settings.production

其中production.py是一个包含设置文件夹中特定于生产的设置的文件。

My Mac OS didn’t like that it didn’t find the env variable set in the settings file:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')

but after adding the env var to my local Mac OS dev environment, the error disappeared:

export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'

In my case, I also needed to add the --settings param:

python3 manage.py check --deploy --settings myappname.settings.production

where production.py is a file containing production specific settings inside a settings folder.


回答 17

对我来说,问题是要get_text_noop反复使用LANGUAGES。

改变中

LANGUAGES = (
    ('en-gb', get_text_noop('British English')),
    ('fr', get_text_noop('French')),
)

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en-gb', _('British English')),
    ('fr', _('French')),
)

在基本设置文件中解决了ImproperlyConfigured: The SECRET_KEY setting must not be empty异常。

The issue for me was calling get_text_noop in the LANGUAGES iterable.

Changing

LANGUAGES = (
    ('en-gb', get_text_noop('British English')),
    ('fr', get_text_noop('French')),
)

to

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en-gb', _('British English')),
    ('fr', _('French')),
)

in the base settings file resolved the ImproperlyConfigured: The SECRET_KEY setting must not be empty exception.


回答 18

我通过在settings.py中的注释行解决了上述问题

SECRET_KEY=os.environ.get('SECRET_KEY')

SECRET_KEY 在我的声明 ~/.bashrc文件中(对于Linux Ubuntu用户)

为了在我的本地计算机上进行开发,我没有使用evironmnet变量

SECRET_KEY = '(i9b4aes#h1)m3h_8jh^duxrdh$4pu8-q5vkba2yf$ptd1lev_'

上面的线没有给出错误

I solved the above problem by commenting the line in my settings.py

SECRET_KEY=os.environ.get('SECRET_KEY')

SECRET_KEY declared in my ~/.bashrc file(for linux Ubuntu users)

For development purpose on my localmachine I did not use evironmnet variable

SECRET_KEY = '(i9b4aes#h1)m3h_8jh^duxrdh$4pu8-q5vkba2yf$ptd1lev_'

above line didn’t give the error


回答 19

就我而言,在设置Github操作时,我只是忘记了将env变量添加到yml文件中:

jobs:
  build:
    env:
     VAR1: 1
     VAR2: 5

In my case, while setting up a Github action I just forgot to add the env variables to the yml file:

jobs:
  build:
    env:
     VAR1: 1
     VAR2: 5

回答 20

答案如此之多的原因是,该异常可能与SECRET_KEY没有任何关系。可能是一个较早的exceptions正在被吞噬。使用DEBUG = True打开调试以查看真正的异常。

The reason why there are so many different answers is because the exception probably doesn’t have anything to do with the SECRET_KEY. It is probably an earlier exception that is being swallowed. Turn on debugging using DEBUG=True to see the real exception.


回答 21

就我而言,经过长时间的搜索,我发现您的Django设置(设置>语言和框架> Django)中的PyCharm具有未定义的配置文件字段。您应该使该字段指向项目的设置文件。然后,您必须打开“运行/调试”设置并删除环境变量DJANGO_SETTINGS_MODULE =现有路径。

发生这种情况是因为PyCharm中的Django插件会强制配置框架。因此,没有必要配置任何os.environ.setdefault(’DJANGO_SETTINGS_MODULE’,’myapp.settings’)

In my case, after a long search I found that PyCharm in your Django settings (Settings > Languages & Frameworks > Django) had the configuration file field undefined. You should make this field point to your project’s settings file. Then, you must open the Run / Debug settings and remove the environment variable DJANGO_SETTINGS_MODULE = existing path.

This happens because the Django plugin in PyCharm forces the configuration of the framework. So there is no point in configuring any os.environ.setdefault(‘DJANGO_SETTINGS_MODULE’, ‘myapp.settings’)


回答 22

导入base.py __init__.py 单独确保您不会再次重复相同的配置!。

设置环境变量 SET DJANGO_DEVELOPMENT =dev

settings/
  __init__.py
  base.py
  local.py
  production.py

__init__.py

from .base import *
if os.environ.get('DJANGO_DEVELOPMENT')=='prod':
   from .production import *
else:
   from .local import *

在已base.py配置的全局配置中。除了数据库。喜欢

SECRET_KEY, ALLOWED_HOSTS,INSTALLED_APPS,MIDDLEWARE .. etc....

local.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'database',
    'USER': 'postgres',
    'PASSWORD': 'password',
    'HOST': 'localhost',
    'PORT': '5432',
}
}

Import base.py in __init__.py alone. make sure you won’t repeat the same configuration again!.

set environment variable SET DJANGO_DEVELOPMENT =dev

settings/
  __init__.py
  base.py
  local.py
  production.py

In __init__.py

from .base import *
if os.environ.get('DJANGO_DEVELOPMENT')=='prod':
   from .production import *
else:
   from .local import *

In base.py configured the global configurations. except for Database. like

SECRET_KEY, ALLOWED_HOSTS,INSTALLED_APPS,MIDDLEWARE .. etc....

In local.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'database',
    'USER': 'postgres',
    'PASSWORD': 'password',
    'HOST': 'localhost',
    'PORT': '5432',
}
}

回答 23

我来这里时正面临着同样的问题,因此我一直在寻找答案,但是这里没有答案对我有用。然后,在其他网站中搜索后,我偶然发现了这个简单的修复方法。对我有用

wsgi.py

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings')

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings.dev')

I came here looking for answer as I was facing the same issues, none of the answers here worked for me. Then after searching in other websites i stumbled upon this simple fix. It worked for me

wsgi.py

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings')

to

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings.dev')

Python:您将如何保存一个简单的设置/配置文件?

问题:Python:您将如何保存一个简单的设置/配置文件?

我不在乎,如果是JSONpickleYAML,或什么的。

我见过的所有其他实现都不兼容前向,因此,如果我有一个配置文件,在代码中添加一个新密钥,然后加载该配置文件,它将崩溃。

有没有简单的方法可以做到这一点?

I don’t care if it’s JSON, pickle, YAML, or whatever.

All other implementations I have seen are not forwards compatible, so if I have a config file, add a new key in the code, then load that config file, it’ll just crash.

Are there any simple way to do this?


回答 0

python中的配置文件

有多种方法可以执行此操作,具体取决于所需的文件格式。

ConfigParser [.ini格式]

除非有令人信服的理由使用其他格式,否则我将使用标准的configparser方法。

像这样写一个文件:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')

with open('config.ini', 'w') as f:
    config.write(f)

文件格式非常简单,其中的部分用方括号标记:

[main]
key1 = value1
key2 = value2
key3 = value3

可以从文件中提取值,如下所示:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')

print config.get('main', 'key1') # -> "value1"
print config.get('main', 'key2') # -> "value2"
print config.get('main', 'key3') # -> "value3"

# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')

# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')

JSON [.json格式]

JSON数据可能非常复杂,并且具有高度可移植的优势。

将数据写入文件:

import json

config = {'key1': 'value1', 'key2': 'value2'}

with open('config.json', 'w') as f:
    json.dump(config, f)

从文件读取数据:

import json

with open('config.json', 'r') as f:
    config = json.load(f)

#edit the data
config['key3'] = 'value3'

#write it back to the file
with open('config.json', 'w') as f:
    json.dump(config, f)

YAML

这个答案提供一个基本的YAML示例。可以在pyYAML网站上找到更多详细信息。

Configuration files in python

There are several ways to do this depending on the file format required.

ConfigParser [.ini format]

I would use the standard configparser approach unless there were compelling reasons to use a different format.

Write a file like so:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')
config.add_section('main')
config.set('main', 'key1', 'value1')
config.set('main', 'key2', 'value2')
config.set('main', 'key3', 'value3')

with open('config.ini', 'w') as f:
    config.write(f)

The file format is very simple with sections marked out in square brackets:

[main]
key1 = value1
key2 = value2
key3 = value3

Values can be extracted from the file like so:

# python 2.x
# from ConfigParser import SafeConfigParser
# config = SafeConfigParser()

# python 3.x
from configparser import ConfigParser
config = ConfigParser()

config.read('config.ini')

print config.get('main', 'key1') # -> "value1"
print config.get('main', 'key2') # -> "value2"
print config.get('main', 'key3') # -> "value3"

# getfloat() raises an exception if the value is not a float
a_float = config.getfloat('main', 'a_float')

# getint() and getboolean() also do this for their respective types
an_int = config.getint('main', 'an_int')

JSON [.json format]

JSON data can be very complex and has the advantage of being highly portable.

Write data to a file:

import json

config = {'key1': 'value1', 'key2': 'value2'}

with open('config.json', 'w') as f:
    json.dump(config, f)

Read data from a file:

import json

with open('config.json', 'r') as f:
    config = json.load(f)

#edit the data
config['key3'] = 'value3'

#write it back to the file
with open('config.json', 'w') as f:
    json.dump(config, f)

YAML

A basic YAML example is provided in this answer. More details can be found on the pyYAML website.


回答 1

ConfigParser Basic示例

该文件可以像这样加载和使用:

#!/usr/bin/env python

import ConfigParser
import io

# Load the configuration file
with open("config.yml") as f:
    sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))

# List all contents
print("List all contents")
for section in config.sections():
    print("Section: %s" % section)
    for options in config.options(section):
        print("x %s:::%s:::%s" % (options,
                                  config.get(section, options),
                                  str(type(options))))

# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous'))  # Just get the value
print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?

哪个输出

List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>

Print some contents
yes
True

如您所见,您可以使用易于读写的标准数据格式。诸如getboolean和getint之类的方法允许您获取数据类型,而不是简单的字符串。

编写配置

import os
configfile_name = "config.yaml"

# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
    # Create the configuration file as it doesn't exist yet
    cfgfile = open(configfile_name, 'w')

    # Add content to the file
    Config = ConfigParser.ConfigParser()
    Config.add_section('mysql')
    Config.set('mysql', 'host', 'localhost')
    Config.set('mysql', 'user', 'root')
    Config.set('mysql', 'passwd', 'my secret password')
    Config.set('mysql', 'db', 'write-math')
    Config.add_section('other')
    Config.set('other',
               'preprocessing_queue',
               ['preprocessing.scale_and_center',
                'preprocessing.dot_reduction',
                'preprocessing.connect_lines'])
    Config.set('other', 'use_anonymous', True)
    Config.write(cfgfile)
    cfgfile.close()

结果是

[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math

[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True

XML基本示例

似乎Python社区根本不使用配置文件。但是,解析/编写XML很容易,并且使用Python可以有很多可能性。一个是BeautifulSoup:

from BeautifulSoup import BeautifulSoup

with open("config.xml") as f:
    content = f.read()

y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
    print(tag)

config.xml可能看起来像这样

<config>
    <mysql>
        <host>localhost</host>
        <user>root</user>
        <passwd>my secret password</passwd>
        <db>write-math</db>
    </mysql>
    <other>
        <preprocessing_queue>
            <li>preprocessing.scale_and_center</li>
            <li>preprocessing.dot_reduction</li>
            <li>preprocessing.connect_lines</li>
        </preprocessing_queue>
        <use_anonymous value="true" />
    </other>
</config>

ConfigParser Basic example

The file can be loaded and used like this:

#!/usr/bin/env python

import ConfigParser
import io

# Load the configuration file
with open("config.yml") as f:
    sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))

# List all contents
print("List all contents")
for section in config.sections():
    print("Section: %s" % section)
    for options in config.options(section):
        print("x %s:::%s:::%s" % (options,
                                  config.get(section, options),
                                  str(type(options))))

# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous'))  # Just get the value
print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?

which outputs

List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>

Print some contents
yes
True

As you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.

Writing configuration

import os
configfile_name = "config.yaml"

# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
    # Create the configuration file as it doesn't exist yet
    cfgfile = open(configfile_name, 'w')

    # Add content to the file
    Config = ConfigParser.ConfigParser()
    Config.add_section('mysql')
    Config.set('mysql', 'host', 'localhost')
    Config.set('mysql', 'user', 'root')
    Config.set('mysql', 'passwd', 'my secret password')
    Config.set('mysql', 'db', 'write-math')
    Config.add_section('other')
    Config.set('other',
               'preprocessing_queue',
               ['preprocessing.scale_and_center',
                'preprocessing.dot_reduction',
                'preprocessing.connect_lines'])
    Config.set('other', 'use_anonymous', True)
    Config.write(cfgfile)
    cfgfile.close()

results in

[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math

[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True

XML Basic example

Seems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:

from BeautifulSoup import BeautifulSoup

with open("config.xml") as f:
    content = f.read()

y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
    print(tag)

where the config.xml might look like this

<config>
    <mysql>
        <host>localhost</host>
        <user>root</user>
        <passwd>my secret password</passwd>
        <db>write-math</db>
    </mysql>
    <other>
        <preprocessing_queue>
            <li>preprocessing.scale_and_center</li>
            <li>preprocessing.dot_reduction</li>
            <li>preprocessing.connect_lines</li>
        </preprocessing_queue>
        <use_anonymous value="true" />
    </other>
</config>

回答 2

如果要使用INI文件之类的东西来保存设置,请考虑使用configparser,它可以从文本文件加载键值对,并可以轻松地写回该文件。

INI文件的格式为:

[Section]
key = value
key with spaces = somevalue

If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.

INI file has the format:

[Section]
key = value
key with spaces = somevalue

回答 3

保存并加载字典。您将拥有任意键,值和任意数量的键,值对。

Save and load a dictionary. You will have arbitrary keys, values and arbitrary number of key, values pairs.


回答 4

尝试使用ReadSettings

from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"

Try using ReadSettings:

from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"

回答 5

尝试使用cfg4py

  1. 分层设计,支持多种环境,因此切勿将开发人员设置与生产站点设置混淆。
  2. 代码完成。Cfg4py会将您的Yaml转换为python类,然后在您键入代码时可以完成代码。
  3. 还有很多..

免责声明:我是这个模块的作者

try using cfg4py:

  1. Hierarchichal design, mulitiple env supported, so never mess up dev settings with production site settings.
  2. Code completion. Cfg4py will convert your yaml into a python class, then code completion is available while you typing your code.
  3. many more..

DISCLAIMER: I’m the author of this module


在Python中使用设置文件的最佳做法是什么?[关闭]

问题:在Python中使用设置文件的最佳做法是什么?[关闭]

我有一个运行有很多参数的命令行脚本。现在到了我有太多参数的地步,我也想以字典形式有一些参数。

因此,为了简化操作,我想使用设置文件来运行脚本。我真的不知道该使用什么库来解析文件。最佳做法是什么?我当然可以自己动手做一些事情,但是如果有图书馆可以帮助我,我会不胜枚举。

一些“需求”:

  • 与其使用pickle我,我不希望它是一个易于阅读和编辑的简单文本文件。
  • 我希望能够在其中添加类似字典的数据,即应支持某种形式的嵌套。

简化的伪示例文件:

truck:
    color: blue
    brand: ford
city: new york
cabriolet:
    color: black
    engine:
        cylinders: 8
        placement: mid
    doors: 2

I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too.

So in order to simplify things I would like to run the script with a settings file instead. I don’t really know what libraries to use for the parsing of the file. What’s the best practice for doing this? I could of course hammer something out myself, but if there is some library for this, I’m all ears.

A few ‘demands’:

  • Rather than using pickle I would like it to be a straight forward text file that can easily be read and edited.
  • I want to be able to add dictionary-like data in it, i.e., some form of nesting should be supported.

A simplified pseudo example file:

truck:
    color: blue
    brand: ford
city: new york
cabriolet:
    color: black
    engine:
        cylinders: 8
        placement: mid
    doors: 2

回答 0

您可以有一个常规的Python模块,例如config.py,如下所示:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

并像这样使用它:

import config
print config.truck['color']  

You can have a regular Python module, say config.py, like this:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

and use it like this:

import config
print config.truck['color']  

回答 1

您提供的样本配置实际上是有效的YAML。实际上,YAML可以满足您的所有需求,并以多种语言实现,并且非常人性化。我强烈建议您使用它。该PyYAML项目提供了一个很好的Python模块,实现YAML。

使用yaml模块非常简单:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

回答 2

我发现这是最有用和易于使用的 https://wiki.python.org/moin/ConfigParserExamples

您只需创建一个“ myfile.ini”,例如:

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

[SectionTwo]
FavoriteColor=Green
[SectionThree]
FamilyName: Johnson

[Others]
Route: 66

并像这样检索数据:

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("myfile.ini")
['c:\\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.options('SectionOne')
['Status', 'Name', 'Value', 'Age', 'Single']
>>> Config.get('SectionOne', 'Status')
'Single'

I Found this the most useful and easy to use https://wiki.python.org/moin/ConfigParserExamples

You just create a “myfile.ini” like:

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

[SectionTwo]
FavoriteColor=Green
[SectionThree]
FamilyName: Johnson

[Others]
Route: 66

And retrieve the data like:

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("myfile.ini")
['c:\\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.options('SectionOne')
['Status', 'Name', 'Value', 'Age', 'Single']
>>> Config.get('SectionOne', 'Status')
'Single'

回答 3

Yaml和Json是存储设置/配置的最简单,最常用的文件格式。PyYaml可用于解析yaml。Json已经从2.5开始成为python的一部分。Yaml是Json的超集。Json将解决大多数使用情况,但需要转义的多行字符串除外。Yaml也会处理这些情况。

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}

Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}