Hey there,
we currently deploy our prototype on PythonAnywhere. We work with Django and use mongoengine for connections to MongoDB Atlas.
The problem is, that Atlas requires to whitelist the IP but PythonAnywhere does not give me a static IP address - it depends on the time the code of the Django application runs.
Whitelisting 0.0.0.0/0 is too risky as we don’t want to open connection from anywhere.
PythonAnywhere recommends to use some sort of atlas_api_key to request a whitelist of the actual IP but I don’t know where I can generate this API key. Is this with a service like Realm? Or might this code example just be out of date? Is this approach even more secure?
Here is the link to the code example I found on PythonAnywhere
https://help.pythonanywhere.com/pages/MongoDB/
import requests
from requests.auth import HTTPDigestAuth
from ipify import get_ip
atlas_group_id = "<your group ID aka project ID -- check the Project / Settings section inside Atlas>"
atlas_username = "<your atlas username/email, eg. jane@example.com>"
atlas_api_key = "<your atlas API key>"
ip = get_ip()
resp = requests.post(
"https://cloud.mongodb.com/api/atlas/v1.0/groups/{atlas_group_id}/whitelist".format(atlas_group_id=atlas_group_id),
auth=HTTPDigestAuth(atlas_username, atlas_api_key),
json=[{'ipAddress': ip, 'comment': 'From PythonAnywhere'}] # the comment is optional
)
if resp.status_code in (200, 201):
print("MongoDB Atlas whitelist request successful", flush=True)
else:
print(
"MongoDB Atlas whitelist request problem: status code was {status_code}, content was {content}".format(
status_code=resp.status_code, content=resp.content
),
flush=True
)