How to connect Django Rest-api with MongoDB? - django

I'm trying to connect Django rest-api with mongo database which i created on mlab.com. Below is my code which I define in settings.py file in my Django rest-api.
MONGODB_DATABASES = {
'default': {
'NAME': 'dummy',
'HOST': os.environ.get('MONGO_HOST',
'mongodb://dummyuser:dummypassword#ds125851.mlab.com:25851/dummy'),
}
}
mongoengine.connection(
db='dummy',
host=os.environ.get('MONGO_HOST',
'mongodb://dummyuser:dummypassword#ds125851.mlab.com:25851/dummy'),
)
When I run this api I got this error
host=os.environ.get('MONGO_HOST', 'mongodb://dummyuser:dummypassword#ds125851.mlab.com
:25851/dummy'),
typeError: 'module' object is not callable
I tried to search for solutions online but I found examples which were for older versions. I'm using Djangorestframework2.0.7, MongoDB3.4 and mongoengine0.15. I couldn't find any answer for this versions. I tried to connect this api to the local database and I got same error. How can I solve it?

I have been successfully connected django rest-api with mongodb. Here is the solution that works for me.
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'dummy',
'HOST': 'localhost',
}
}
MONGODB_DATABASES = {
'db': 'dummy',
'host': 'localhost',
'port': 27017,
}
Here is the link for more information.
http://blog.tomjohnhall.com/python-3-6-django-2-0-and-mongodb-3-4-3-6/

You can try these steps to connect your django 2.0 or more with MongoDB database:
1) Install mongoengine for django 2.0
pip install -e git+https://github.com/MongoEngine/django-mongoengine.git#egg=django-mongoengine
2)Add these in your settings file:
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)
},
}
You can find the details for querying the database here

Related

Connecting a Neo4j graph database to a Django REST API app

I am trying to connect a remote Neo4j database to a Django app with a REST API.
I am trying to specify the database in the settings.py file using the following code:
DATABASES = {
'default': {
'NAME': 'papers.db',
'ENGINE': 'django.db.backends.sqlite3',
'USER': '',
'PASSWORD': '',
'PORT': '',
},
}
I would like to know:
What python libraries need to be installed in order to do this?
What is the 'ENGINE' that needs to be specified in the code above?
The Neo4j database has a URI, but does not provide us with an IP address - am I able to use this URI?
I am confident that I know what the other parameters need to be.
Thanks in advance

Error in Connecting Multiple Database Django ( 'DatabaseOperations' object has no attribute 'geo_db_type' )

I am using multiple databases in Django,
On the current server, PostGIS is installed and am trying to connect POSTGRESQL from another server,
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'db_name_1',
'USER': 'user_name_1',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
'users_db' : {
'NAME' : 'db_name_2',
'ENGINE' : 'django.db.backends.postgresql_psycopg2',
'HOST' : '',
'PORT' : '',
'USER' : 'user_name_2',
'PASSWORD' : '',
},
# 'users_db' : dj_database_url.config(default='postgres://user_name_2:password_2#host_2:0000/db_name_2')
}
Now as per documentation.
Error
python3 manage.py migrate --database='users_db'
AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
UPDATE
As per other StackOverflow pages, I found dj-database-url i used it but still problem persists.
for dj-database-url
'users_db' : dj_database_url.config(default='postgres://user_name_2:password_2#host_2:0000/db_name_2')
Any help will be appreciated,
Thanks & Regards
You are trying to migrate geospatial enabled objects to non geospatial database...when connected another database contrib.gis.db.backend.postgis should be on the second database to only the host and ports are to change

aws lambda deployed by zappa is not able to connect to remote database

I'm deploying a django project using zappa to aws-lambda and using mongodb atlas as my database.
I'm tring to connect to the database using djongo.
I set my django_setting in the zappa_settings.json to my project's django settings.
The connection to the database with this settings works just fine in localhost. when deploying, it fails to connect to the server and I suspect that it tries to connect to a default local db (the db sent to mongo_client.py isnt valid or something and it needs to connect to default HOST).
The actual error I get is:
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused
The above exception was the direct cause of the following exception:
djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT
If anyone has an idea I'd would love to hear.
attaching the settings with some fields unset (but set at my settings)
Django settings (database part):
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'db',
'HOST': 'mongodb://<username>:<password>#<>
'USER': 'username',
'PASSWORD': 'password',
}
}
zappa_settings:
{
"dev":
{
"aws_region": "eu-west-1",
"django_settings": settings,
"profile_name": "default",
"project_name": name,
"runtime": "python3.6",
"s3_bucket": bucket,
"timeout_seconds": 900,
"manage_roles": false,
"role_name": name,
"role_arn": arn,
"slim_handler": true
}
}
Try this
'default': {
'ENGINE': 'djongo',
'CLIENT': {
'host': 'mongodb+srv://url',
'username': '<username>',
'password': '<password>',
'name':'<db_name>'
}
}

How to configure djongo for production with admin account?

I managed to get djongo working in my local computer but when I push it to production, I need to set up an admin account for mongo so that my DB doesnt get hacked (again, sigh). Ive searched for a solution for a couple of days, without success.
This is currently the code I have, but its not working:
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'db_name',
'HOST': 'localhost',
'USERNAME': 'username',
'PASSWORD': 'password',
}
}
1) How can I configure djongo to access a DB with a username/password? I am only getting errors telling me that it wasnt able to log in to mongo.
2) Ive read a bit about "mongoengine", would you recommend I use that instead of djongo? Why?
Use this format for the Database Configuration
DATABASES = {
'default': {
"ENGINE": "djongo",
"CLIENT": {
"host": "mongodb+srv://<user_name>:<password>#<host_url>/?retryWrites=true&w=majority",
"username": "<user_name>",
"password": "<password>",
"name": "<db_name>",
"authMechanism": "SCRAM-SHA-1", #Add this line if you are using Mongo Atlas Cloud DB
},
}
}

django unit testing on multiple databases

I'm working on a django project where all my unit test cases were working perfectly.
Ass soon as I introduced a second database all my test cases that inherit from TestCase are broken. At this stage I haven't build any test case for that second database but my router is working fine.
When I run the tests I get the error,
"KeyError: 'SUPPORTS_TRANSACTIONS'"
It appears to me that is trying to check that that all the databases that I've got setup support transactions but the second database is never created.
Any ideas on how to have the test script to build the second database.
I realise this is quite an old thread, but I ran into it with the same issue, and my resolve was adding the multi_db = True flag to my testcase, e.g:
class TestThingWithMultipleDatabases(TestCase):
multi_db = True
def test_thing(self):
pass
Source https://github.com/django/django/blob/master/django/test/testcases.py#L861
This causes django to call flush on all databases (or rollback if they support transactions)
I too am using a db router
I'm afraid I cant find this in Django's documentation, so no link for that
yes I had a similar problem... my fix was to set 'SUPPORTS_TRANSACTIONS': True for each of the database connections in the settings file. Not sure if this is the correct way to fix it, but it worked for me.
'SUPPORTS_TRANSACTIONS':True worked for me too.
However I have a kind of weird multiple db setup using database routers.
#user298404: how does your multiple db setup look like?
ps. sorry; not enough points for comment...
Here is a multiple db setup that I currently have in production:
DATABASES = {
# 'default' is used as the WRITE (master) connection
DB_PRIMARY_MASTER: {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'main',
'USER': 'main_write',
'PASSWORD': 'XXXX',
'HOST': 'db-master',
'PORT': '3306',
'SUPPORTS_TRANSACTIONS': True,
},
# Slave connections are READONLY
DB_PRIMARY_SLAVE: {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'main',
'USER': 'main_read',
'PASSWORD': 'XXXX',
'HOST': 'db-slave',
'PORT': '3306',
'TEST_MIRROR': DB_PRIMARY_MASTER,
'SUPPORTS_TRANSACTIONS': True,
},
# 'mail_default' is used as the WRITE (master) connection for the mail database
DB_MAIL_MASTER: {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbmail',
'USER': 'dbmail_write',
'PASSWORD': 'XXXX',
'HOST': 'db-mail-master',
'PORT': '3306',
'SUPPORTS_TRANSACTIONS': True,
},
# Slave connections are READONLY
DB_MAIL_SLAVE: {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbmail',
'USER': 'dbmail_read',
'PASSWORD': 'XXXX',
'HOST': 'db-mail-slave',
'PORT': '3306',
'TEST_MIRROR': DB_MAIL_MASTER,
'SUPPORTS_TRANSACTIONS': True,
},
}
DB_PRIMARY_MASTER, DB_PRIMARY_SLAVE, DB_MAIL_MASTER, and DB_MAIL_SLAVE are all string constants so that they can be used in my database router.
Hint: DB_PRIMARY_MASTER='default'
I hope this helps!
Referring to that link
Django doc Multi-Db
you can:
from django.test import TransactionTestCase
class TestMyViews(TransactionTestCase):
databases = {'default', 'other'} # {'__all__'} shold work too
def test_index_page_view(self):
call_some_test_code()
thanks to
#sih4sing5hog5