python - 使用Docker容器运行django应用失败

标签 python django docker docker-compose containers

我正在尝试在localhost:8000上运行Django应用程序。
我有一个创建3个容器的docker-compose.yml文件:

  • badgr-server_api
  • badgr-server_memcached
  • badgr-server_db_

  • 当我运行docker-compose up时,它说开始两个容器并创建第三个容器(badgr-server_api),而我只看到memchaced和db正在运行,请参见屏幕截图。我尝试删除badgr-server_api并再次运行它,我尝试删除该图像。
    我也再次运行了docker-compose build,但是我无法使其运行。我希望有人可以帮忙。
    docker-compose up screenshot
    运行docker之后,我还运行了以下命令:
    docker-compose exec api python /badgr_server/manage.py migrate
    
    并得到以下结果:
    Traceback (most recent call last):
      File "/badgr_server/manage.py", line 13, in <module>
       
      File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 212, in get_connection_params
        isolation_level = options.pop('isolation_level', 'read committed')
    TypeError: pop() takes no arguments (2 given)
    
    这是我的docker-compose.yml:
    # A dockerized badgr-server stack for development
    version: '3.3'
    services:
    
      # this container mirrors in the app code and runs the django dev server
      api:
        build:
          context: .
          dockerfile: .docker/Dockerfile.dev.api
        depends_on:
          - "db"
          - "memcached"
        command: /badgr_server/manage.py runserver 0.0.0.0:8000
        volumes:
          - ./apps:/badgr_server/apps
          - ./manage.py:/badgr_server/manage.py
          - ./.docker/etc/settings_local.dev.py:/badgr_server/apps/mainsite/settings_local.py
        networks:
          - badgr
        ports:
          - "8000:8000"
    
      # this container runs memcached
      memcached:
        image: 'bitnami/memcached:latest'
        expose:
          - "11211"
        networks:
          - badgr
    
      # this container runs mysql (database)
      db:
        image: mysql:5.6.39
        volumes:
          - badgr_server_dev_db:/var/lib/mysql:rw
          - ./.docker/etc/init.sql:/docker-entrypoint-initdb.d/init.sql
        environment:
          - "MYSQL_PASSWORD=password"
          - "MYSQL_HOST=db"
          - "MYSQL_ROOT_PASSWORD=password"
        expose:
          - "3306"
        networks:
          - badgr
    
    networks:
      badgr:
        driver: bridge
    
    volumes:
      badgr_server_dev_db:
    
    > import random import string from .settings import * from mainsite
    > import TOP_DIR
    > 
    > DEBUG = False DEBUG_ERRORS = DEBUG DEBUG_STATIC = DEBUG DEBUG_MEDIA =
    > DEBUG
    > 
    > TIME_ZONE = 'America/Los_Angeles' LANGUAGE_CODE = 'en-us'
    > 
    > 
    > ##
    > #
    > # Database Configuration
    > #
    > ## DATABASES = {
    >     'default': {
    >         'ENGINE': 'django.db.backends.mysql',
    >         'NAME': 'badgr',
    >         'USER': 'root',
    >         'PASSWORD': 'password',
    >         'HOST': 'db',
    >         'PORT': '',
    >         'OPTIONS': {
    >             "SET character_set_connection=utf8mb3, collation_connection=utf8_unicode_ci"
    >             #            ,  # Uncomment when using MySQL to ensure consistency across servers
    >         },
    >     } }
    > 
    > 
    > ###
    > #
    > # CACHE
    > #
    > ### CACHES = {
    >      'default': {
    >          'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
    >          'LOCATION': 'memcached:11211',
    >          'KEY_FUNCTION': 'mainsite.utils.filter_cache_key'
    >      }  }
    > 
    > 
    > 
    > ###
    > #
    > # Email Configuration
    > #
    > ### DEFAULT_FROM_EMAIL = 'noreply@example.com'  # e.g. "noreply@example.com" EMAIL_BACKEND =
    > 'django.core.mail.backends.console.EmailBackend'
    > 
    > 
    > ###
    > #
    > # Celery Asynchronous Task Processing (Optional)
    > #
    > ### CELERY_RESULT_BACKEND = None
    > # Run celery tasks in same thread as webserver (True means that asynchronous processing is OFF) CELERY_ALWAYS_EAGER = True
    > 
    > 
    > ###
    > #
    > # Application Options Configuration
    > #
    > ### HTTP_ORIGIN = 'http://localhost:8000' ALLOWED_HOSTS = ['*'] STATIC_URL = HTTP_ORIGIN + '/static/'
    > 
    > CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = (
    >     'http://localhost:4200', )
    > 
    > # Optionally restrict issuer creation to accounts that have the 'issuer.add_issuer' permission BADGR_APPROVED_ISSUERS_ONLY = False
    > 
    > # Automatically send an email the first time that recipient identifier (email type) has been used on the system.
    > GDPR_COMPLIANCE_NOTIFY_ON_FIRST_AWARD = True
    > 
    > SECRET_KEY = ''.join(random.choice(string.ascii_uppercase +
    > string.digits) for _ in range(40)) UNSUBSCRIBE_KEY =
    > ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in
    > range(40)) UNSUBSCRIBE_SECRET_KEY = str(SECRET_KEY)
    > 
    > 
    > ###
    > #
    > # Logging
    > #
    > ### LOGS_DIR = os.path.join(TOP_DIR, 'logs') if not os.path.exists(LOGS_DIR):
    >     os.makedirs(LOGS_DIR) LOGGING = {
    >     'version': 1,
    >     'disable_existing_loggers': False,
    >     'handlers': {
    >         'mail_admins': {
    >             'level': 'ERROR',
    >             'filters': [],
    >             'class': 'django.utils.log.AdminEmailHandler'
    >         },
    > 
    >         # badgr events log to disk by default
    >         'badgr_events': {
    >             'level': 'INFO',
    >             'formatter': 'json',
    >             'class': 'logging.FileHandler',
    >             'filename': os.path.join(LOGS_DIR, 'badgr_events.log')
    >         }
    >     },
    >     'loggers': {
    >         'django.request': {
    >             'handlers': ['mail_admins'],
    >             'level': 'ERROR',
    >             'propagate': True,
    >         },
    > 
    >         # Badgr.Events emits all badge related activity
    >         'Badgr.Events': {
    >             'handlers': ['badgr_events'],
    >             'level': 'INFO',
    >             'propagate': False,
    > 
    >         }
    > 
    >     },
    >     'formatters': {
    >         'default': {
    >             'format': '%(asctime)s %(levelname)s %(module)s %(message)s'
    >         },
    >         'json': {
    >             '()': 'mainsite.formatters.JsonFormatter',
    >             'format': '%(asctime)s',
    >             'datefmt': '%Y-%m-%dT%H:%M:%S%z',
    >         }
    >     }, }
    

    最佳答案

    您的DATABASES.default.OPTIONS应该是字典,而不是集合,如果不习惯,则很难看到两者之间的区别:

    In [5]: type({'key': 'value'})
    Out[5]: dict
    
    In [6]: type({'key and no value'})
    Out[6]: set
    
    这就是为什么收到pop() takes no arguments (2 given)错误消息的原因,因为这是set.pop的工作方式:https://docs.python.org/3.7/library/stdtypes.html#frozenset.pop
    通过使用格式正确的字典,您应该能够使其工作而不用注释选项:
    DATABASES = {
        "default": {
            ...
            "OPTIONS": {
                "character_set_connection": "utf8mb3",
                "collation_connection": "utf8_unicode_ci",
            },
        }
    }
    
    我不确定确切的语法,尤其是值"utf8mb3""utf8_unicode_ci"应该是我认为的枚举。我没有mysql db可以尝试,因此您必须自己找到它。

    关于python - 使用Docker容器运行django应用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63850707/

    相关文章:

    php - 对网络集体编程感兴趣——Ruby 或 Python 或 PHP?

    python - 使用中的 Gunicorn 连接 : ('0.0.0.0' , 5000)

    python - 如何使用带有数据的数据库在 Django 中运行测试?

    python - 需要帮助将 Paypal API 返回 URL 与 django 中的正则表达式匹配

    python - uWSGI native 异步 websockets 和 redis 的错误文件描述符

    python - 获取命令行参数作为字符串

    python - ImportError:没有名为weather_Core_Engine.weather_DB_Handler的模块

    linux - 在 Linux RHEL 中启动时 Docker 守护进程抛出错误

    docker - 端口绑定(bind)在 Windows 上的 docker 中不起作用

    docker - 使用Docker配置Kibana监控