Learn how to securely route Python PyMongo database traffic through a QuotaGuard Shield proxy using QGTunnel with zero code changes.
This example shows how to connect to a MongoDB instance through a QuotaGuard Shield proxy using QGTunnel.
QGTunnel wraps your process and automatically routes all outgoing TCP connections through the Shield proxy — no code changes to your application required.
pip install pymongo
curl https://s3.amazonaws.com/quotaguard/qgtunnel-latest.tar.gz | tar xz
1. QUOTAGUARDSHIELD_URL: Your QuotaGuard Shield proxy URL, e.g. https://user:password@us-east-shield-01.quotaguard.com:9294.
Found in your QuotaGuard Dashboard.
2. MONGO_URIA standard mongodb:// or mongodb+srv:// connection string.
QUOTAGUARDSHIELD_URL=https://... MONGO_URI=mongodb://... bin/qgtunnel python app.pydocker build -t qg-shield-python-mongo-qgtunnel-example .
docker run \
-e QUOTAGUARDSHIELD_URL=https://... \
-e MONGO_URI=mongodb://... \
qg-shield-python-mongo-qgtunnel-exampleNote : mongodb+srv:// URIs work fine here because QGTunnel intercepts DNS lookups as well as TCP connections.
import os
import pymongo
from pymongo.errors import ConnectionFailure
MONGO_URI = os.getenv("MONGO_URI")
def test_mongo_connection():
try:
client = pymongo.MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)
client.server_info() # Will attempt to connect to the server
print("Connection Success.")
except ConnectionFailure as e:
print(f"Connection failed: {e}")
if __name__ == "__main__":
test_mongo_connection()# Use an official Python runtime as a parent image
FROM python:latest
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install the required Python packages
RUN pip install --no-cache-dir pymongo
# Download and extract QGTunnel software
RUN curl https://s3.amazonaws.com/quotaguard/qgtunnel-latest.tar.gz | tar xz
# Command to run when the container starts
CMD ["bin/qgtunnel", "python", "app.py"]