【问题标题】:Django can not run 'install_labels' on neo4j DatabaseDjango 无法在 neo4j 数据库上运行“install_labels”
【发布时间】:2022-02-18 01:58:45
【问题描述】:

我正在尝试设置一个 Docker 容器,在前端运行 React,在后端运行 Django,并将 Neo4j 作为数据库。目前所有三个组件都运行正常,但我无法让 Django 连接到 Neo4j 数据库。我可能已经阅读了互联网上的所有教程并尝试了所有的东西,但它总是出现一些错误并且数据库无法访问或拒绝访问。 我也处理了这个tutorial 并相应地创建了模型。但是,当我运行“python manage.py install_labels”时,总是会出错。

错误是: neobolt.exceptions.SecurityError: 无法建立到“EOF 违反协议 (_ssl.c:997)”的安全连接

你们有没有人设置过类似的环境或可以帮助我? 也许 Django 不太适合它....基本上我只想要一个 React 前端和一个 Python 后端与 Neo4j 数据库一起工作。整个事情都请在 Docker 映像中。 后端有没有更好的替代方案?

提前感谢您的帮助!

在下面你可以看到我认为重要的所有文件。

我的 Dockerfile 看起来像这样:

# Django Dockerfile
FROM python:3
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

WORKDIR /myapp

COPY /myapp/django_backend/requirements.txt /myapp/
RUN pip install --no-cache-dir -r requirements.txt

COPY /myapp/django_backend /myapp/
# React Dockerfile
FROM node:17-alpine3.14

WORKDIR /myapp

COPY /myapp/react_frontend /myapp

RUN npm install

CMD ["npm", "start"]

我的 docker-compose 文件:

version: '3.8'

services:
  react:
    image: react_frontend:latest
    restart: unless-stopped
    volumes:
      - ./myapp/react_frontend/public:/myapp/public
      - ./myapp/react_frontend/src:/myapp/src
    ports:
      - 3000:3000

   django:
     image: django_backend:latest
     command: python manage.py runserver 0.0.0.0:8000
     volumes:
       - ./myapp/django_backend:/myapp
     ports:
       - 8000:8000
     expose:
       - 8000
     depends_on:
       - neo4j
     links:
       - neo4j

  neo4j:
    image: neo4j:4.4.3
    restart: unless-stopped
    ports:
      - 7474:7474
      - 7687:7687
    volumes:
      - neo4j_data:/neo4j/data
    environment:
      - NEO4J_AUTH=none
      - encrypted=False

volumes:
  neo4j_data:

我的要求.txt:

Django
djangorestframework
django-cors-headers

psycopg2

# neo4j and django connection
django-neomodel
neomodel
neo4j-driver

还有来自 Django 后端的 settings.py:

from neomodel import config
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(_file_).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+b-r19ofy)&x20j57qzv1f_zn(*6gld6!&bg&g@8=m=hz)8@as'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # for api
    'rest_framework',
    'corsheaders',
    # for connection with database
    'django_neomodel',

    'techstack'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

ROOT_URLCONF = 'django_backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_backend.wsgi.application'

config.DATABASE_URL = 'bolt://neo4j:neo4j@neo4j:7687'
config.ENCRYPTED_CONNECTION = False

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

我还尝试查看是否可以通过 GraphDatabase.driver 访问数据库,并且可行。以下 test.py 文件位于我的容器的顶层,我可以直接从终端运行它,并且成功创建了数据库对象。只有命令“python manage.py install_labels”仍然不起作用并中止并出现错误“neobolt.exceptions.SecurityError:无法建立与“EOF 违反协议(_ssl.c:997)”的安全连接。

# test.py:
from neo4j import GraphDatabase

class HelloWorldExample:

    def __init__(self, uri, user, password):
        self.driver = GraphDatabase.driver(uri, auth=(user, password), encrypted=False)

    def close(self):
        self.driver.close()

    def print_greeting(self, message):
        with self.driver.session() as session:
            greeting = session.write_transaction(self._create_and_return_greeting, message)
            print(greeting)

    @staticmethod
    def _create_and_return_greeting(tx, message):
        result = tx.run("CREATE (a:Greeting) "
                        "SET a.message = $message "
                        "RETURN a.message + ', from node ' + id(a)", message=message)
        return result.single()[0]


# if name == "main":
greeter = HelloWorldExample("bolt://neo4j:7687", "", "")
greeter.print_greeting("hello, world")
greeter.close()

【问题讨论】:

  • 'bolt://neo4j:neo4j@localhost:7687' 指向本地主机,但您的数据库在另一个容器中。尝试使用'bolt://neo4j:neo4j@neo4j:7687'
  • 此外,django 容器位于其自己的网络 neo4j_network 上,但实际的 neo4j 容器位于 Compose 提供的 default 网络上。我建议删除文件中的所有 networks: 块,以便所有内容都在 default 上。
  • 非常感谢您的帮助!网络确实是一个错误,因此只能通过无数次尝试。最初,我没有为两个容器配置任何网络或设置网络。我更新了我的撰写文件并取出了网络。使用地址 'bolt://neo4j:neo4j@neo4j:7687' 我现在得到以下信息:错误消息:neobolt.exceptions.SecurityError: 无法建立到 'EOF 的安全连接违反协议(_ssl.c:第997章
  • 我还尝试在 settings.py 中添加行 'config.ENCRYPTED_CONNECTION = False' 并在数据库中添加 'encrypted=False' 行,但这并没有改变任何东西。

标签: python django docker neo4j neomodel


【解决方案1】:

检查您的 requirements.txt。它说 neo4j-driver>=1.7,

https://neo4j.com/developer/kb/neo4j-supported-versions/

【讨论】:

  • 嘿何塞,感谢您的帮助。我更改了要求,以便它使用最新版本。我还发现我的 Django 实际上可以访问数据库。请看一下我的问题的(新)最后一部分。我不知道到底是什么问题,但不知何故,“python manage.py install_labels”命令不起作用。可能settings.py文件中'config.ENCRYPTED_CONNECTION = False'这行不能正确处理?
猜你喜欢
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多