在Docker上运行的Django中的密码学错误

时间:2019-02-27 18:12:16

标签: python mysql django docker cryptography

我正在尝试部署一个网站,该网站的后端使用Django开发。我设置了两个Docker容器,其中包含Django实例和MySQL实例。我还在容器之间设置了网络以创建通信。问题是当我使用参数MYSQL_ROOT_PASSWORD启动MySQL容器时,Django给了我以下错误:

return Database.connect(**conn_params)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
app    |     return Connection(*args, **kwargs)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
app    |     self.connect()
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 599, in connect
app    |     self._request_authentication()
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 882, in _request_authentication
app    |     auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 264, in caching_sha2_password_auth
app    |     data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key)
app    |   File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 142, in sha2_rsa_encrypt
app    |     raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")
app    | RuntimeError: cryptography is required for sha256_password or caching_sha2_password

我已经检查3306端口在我的PC上是否可用,是的。 另一方面,如果我使用MYSQL_ALLOW_EMPTY_PASSWORD启动MySQL容器,并在settings.py中设置空白密码,则它可以正常工作。

这是我的设置。py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'username',
        'PASSWORD': 'userpwd',
        'HOST': 'db',
        'PORT': '3306'
    }
}

相反,这是我的docker-compose.yml文件

version: "3"
services:
  app:
    build:
      context: .
    container_name: app
    ports:
      - "8000:8000"
    networks:
      - backend_split
    depends_on:
      - db
    restart: always
    volumes:
      - ./app:/app
    command:
      sh -c "python manage.py runserver 0.0.0.0:8000"
  db:
    image: mysql
    container_name: db
    expose:
      - "3306"
    networks:
      - backend_split
    environment:
      - MYSQL_ROOT_PASSWORD=rootpwd
      - MYSQL_DATABASE=databasename
      - MYSQL_USER=username
      - MYSQL_PASSWORD=userpwd

networks:
  backend_split:

我一直被这个错误困扰几天。

谢谢。

2 个答案:

答案 0 :(得分:0)

我已经自己解决了这个问题。我已经打开了各种关于此的stackOverflow主题,但是什么也没有。我搜索了“ pip install cryptography”,但棘手的地方在这里。 因此,在模拟Alpine环境的Docker中,解决方案是将以下代码行添加到Dockerfile中:

RUN apk add gcc
RUN apk add --no-cache libressl-dev musl-dev libffi-dev
RUN pip install --no-cache-dir cryptography==2.1.4
RUN apk del libressl-dev \
        musl-dev \
        libffi-dev

然后...运行。

答案 1 :(得分:0)

您可以通过安装此依赖项来解决此问题:

  1. $ pip install django-cryptographic-fields

  2. 添加然后将“ cryptographic_fields”添加到您的INSTALLED_APPS设置中,如下所示:

INSTALLED_APPS = (
...
'cryptographic_fields',
)