简体   繁体   中英

Heroku Deployment With MongoDB Error: Connection Refused

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused Hello their, I am having a little bit of trouble trying to deploy my Django site in python. I am getting this error(shown above) when trying to connect with my MongoDB atlas database. I read that I have to whitelist my IP, but when I did it did not work. Here is my views.py file:

class Initialize():
    def __init__(self, name):
        self.name = name
        myclient = pymongo.MongoClient('mongodb+srv://<MY Username>:<My Password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority')
        global mydb
        mydb = myclient[f"{self.name}"]
        global userData
        userData = mydb["userData"]
        global authData
        authData = mydb["auth_user"]
        global storesCollection
        storesCollection = mydb["stores"]
        global mycolPostalCodes
        mycolPostalCodes = mydb["postalCodes"]

When I was running my code before I tried deploying it, the code worked fine. Also, here is my settings.py file:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'cluster0',
        'HOST' : 'mongodb+srv://<my username>:<my password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority',
        'USER': '<my username>',
        'PASSWORD': '<my password>',
    }
}

Any help would be much appreciated. Thanks. Please message me for more information if needed.

You need to whitelist the IP of the client, in this case Heroku. Their IP addresses are described here . Whitelisting your home/laptop IP does not allow Heroku to connect to your cluster.

To find out the address of a particular machine you could run eg the following code on the machine in question:

python -c "import urllib; print(urllib.urlopen('https://wtfismyip.com/text').read())"

So, all I had to do was change my settings file. The way that I was connecting to mongodb atlas was outdated. So here is how I connected:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'CLIENT': {
            'host': 'mongodb+srv://{username}:{password}@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority',
            'username': {username},
            'password': {password},
            'authMechanism': 'SCRAM-SHA-1'
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM