将Mongodb与Django连接

时间:2018-10-05 06:59:27

标签: python django mongodb

我正在尝试将mongodb与django连接,但出现此错误

ImproperlyConfigured: 'djongo' isn't an available database backend.
Try using 'django.db.backends.XXX', where XXX is one of:
    'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3'

我已经阅读过帖子,但它们都很老,没有帮助我。我已使用Studio 3T创建了mongodb数据库,数据库名称为 NewDataBase ,用户名为 gsc-30310 ,端口名为 27017 ,主机名为 localhost < / strong>

我使用的版本是:

python3

Django==2.1.1
mongoengine==0.15.3
pymongo==3.7.1

这是我的settings.py文件,请告诉我如何设置新版本的django和python3。谢谢

    """
Django settings for RestUserAPI project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os
import mongoengine

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3==2yxbjdvt+hkqm#*%s7cs4g(_+cus9pdup%bxd*uk03g^&w%'

# 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',

    #RestFrameWork
    'rest_framework',
]

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',
]

ROOT_URLCONF = 'RestUserAPI.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 = 'RestUserAPI.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        #'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE' : '',
        'NAME' : 'local',
        'USER' : 'gsc-30310',
        'PASSWORD': 'gsc-30310',
        'HOST': 'localhost',                      
        'PORT': '27017',
    }
}

# _MONGODB_USER = 'gsc-30310'
# _MONGODB_PASSWD = 'gsc-30310'
# _MONGODB_HOST = '127.0.0.1'
# _MONGODB_NAME = 'NewDataBase'
# _MONGODB_DATABASE_HOST = \
#     'mongodb://%s:%s@%s/%s' \
#     % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
#
# mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)

# Password validation
# https://docs.djangoproject.com/en/2.1/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/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    # 'DEFAULT_PARSER_CLASSES': (
    #     'rest_framework.parsers.JSONParser',
    # )
    'DEFAULT_AUTHENTICATION_CLASSES':[
        'rest_framework.authentication.SessionAuthentication',
    #'rest_framework.authentication.BasicAuthentication'
    ],
    'DEFAULT_PERMISSION_CLASSES':[
        'rest_framework.permissions.AllowAny',
    ]

}

6 个答案:

答案 0 :(得分:1)

在Django视图中使用pymongo:

client = pymongo.MongoClient(MONGO_URI)
mongodb = client[MONGO_DB_NAME]
...
class MongoClassView(View):
   def post(request):
       ...
       mapped_data = {'name': 'John'}
       mongodb.get_collection('mycollection').insert(mapped_data)
       return JsonResponse({})

希望这会有所帮助

答案 1 :(得分:1)

您可以尝试以下步骤将django 2.0或更高版本与MongoDB数据库连接:

1)为django 2.0安装mongoengine

pip install -e git+https://github.com/MongoEngine/django-mongoengine.git#egg=django-mongoengine

2)将它们添加到您的设置文件中:

from mongoengine import *

'django_mongoengine', // Add this line to installed app

MONGODB_DATABASES = {
"default": {
"name": '<db_name>',
"host": 'localhost',
"password": '',
"username": '',
"tz_aware": True, # if you using timezones in django (USE_TZ = True)
},
}

您可以找到查询数据库here

的详细信息

答案 2 :(得分:0)

Django与诸如PostGreSQL,MySQL之类的关系数据库配合良好。每个django设置都需要具有使用“默认”配置定义的数据库配置,它还需要数据库各自的引擎,例如用于PostGreSQL的psycopg2,用于MySQL的mysqlclient-如果您有多个数据库配置,则需要使用数据库路由器检查here参考。如果是MongoDB-如果您确实需要使用MongoDB,则Django官方不支持NoNo数据库,如果您确实需要使用MongoDB,则在视图中创建mongoengine配置,并且可以在settings.py

中定义mongo凭证

答案 3 :(得分:0)

首先感谢您对这个问题的回答和支持。

我同意 Sanchit shreesh katti 的回答,我们可以使用mongoclient和mongoengine连接MongoDB,两者都很好。

我找到了另一种方法,有一个开源项目djongo,并且我正在使用djongo连接MongoDB数据库。 djongo的主要好处是它使您可以使用django提供的所有内容(例如models.Model)。

这是djongo GitHub页面https://github.com/nesdis/djongo

的链接

这是我们需要使用djongo的设置 settings.py

DATABASES = {
'default': {
    'ENGINE': 'djongo',
    'NAME': 'MyDB',
}

}

答案 4 :(得分:0)

使用mongoengine和djongo进行连接。 在settings.py文件中进行以下更改

country1, country2, country3 = input("Write up to three comma-separated countries for which you want to extract data: ").split(",")

答案 5 :(得分:0)

使用djongo连接到您的mongodb: 在venv上使用这些版本(如果要使用虚拟env):

dataclasses==0.1

Django==2.0

djongo==1.2.30

pymongo==3.2

pytz==2018.5

sqlparse==0.2.3

并遵循以下步骤:Connect MongoDB to Django (using djongo)