0% found this document useful (0 votes)
49 views6 pages

Deploying A Django Project Integrated With MongoDB

This document provides a comprehensive guide for deploying a Django project integrated with MongoDB, Django Channels, and Generative AI APIs. It outlines prerequisites, deployment steps, and configurations for server environment, databases, ASGI/WSGI, and reverse proxy setup using Nginx. The guide also includes optional steps for HTTPS configuration and automated deployment using Git.

Uploaded by

Pawan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views6 pages

Deploying A Django Project Integrated With MongoDB

This document provides a comprehensive guide for deploying a Django project integrated with MongoDB, Django Channels, and Generative AI APIs. It outlines prerequisites, deployment steps, and configurations for server environment, databases, ASGI/WSGI, and reverse proxy setup using Nginx. The guide also includes optional steps for HTTPS configuration and automated deployment using Git.

Uploaded by

Pawan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Deploying a Django project integrated with MongoDB, Django Channels, and Generative AI

APIs to production involves several steps. Here’s a comprehensive guide:

Prerequisites

1. Server or Cloud Provider: Choose a cloud provider like AWS, Google Cloud Platform
(GCP), or DigitalOcean. Alternatively, you can use Heroku or Render for simpler
deployments.
2. Domain: Register a domain if you want to access the application with a custom domain.
3. SSL Certificate: For HTTPS, consider using Let’s Encrypt or a service like Cloudflare.

Overview of Deployment Steps

1. Set up the server environment.


2. Configure PostgreSQL or MongoDB databases.
3. Configure Django Channels for WebSockets.
4. Deploy with Gunicorn and Daphne.
5. Use Nginx as a reverse proxy for performance and security.
6. Configure environment variables and secrets.
7. Deploy the code and automate future deployments.

Step 1: Set Up Server Environment

1. Provision the Server:


o Use Ubuntu 20.04 or 22.04 on a cloud provider or a local server.
2. SSH into the Server:

bash
Copy code
ssh your_username@your_server_ip

3. Update and Install Dependencies:

bash
Copy code
sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip python3-venv nginx

Step 2: Configure PostgreSQL or MongoDB

Install and Configure MongoDB

1. Install MongoDB:

bash
Copy code
sudo apt install -y mongodb
2. Configure MongoDB:
o Start MongoDB and ensure it’s running.
o Configure your Django settings to connect to MongoDB.

Install PostgreSQL (Optional)

If you prefer PostgreSQL for relational data:

1. Install PostgreSQL:

bash
Copy code
sudo apt install postgresql postgresql-contrib

2. Configure PostgreSQL:

bash
Copy code
sudo -u postgres psql
CREATE DATABASE your_db_name;
CREATE USER your_user WITH PASSWORD 'your_password';
ALTER ROLE your_user SET client_encoding TO 'utf8';
ALTER ROLE your_user SET default_transaction_isolation TO 'read
committed';
ALTER ROLE your_user SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE your_db_name TO your_user;

Step 3: Install and Configure Python Environment

1. Create a Virtual Environment:

bash
Copy code
python3 -m venv /path/to/your/venv
source /path/to/your/venv/bin/activate

2. Install Project Dependencies:

bash
Copy code
pip install -r requirements.txt

Step 4: Install Gunicorn and Daphne for ASGI

Install Gunicorn for serving HTTP requests and Daphne for handling WebSocket connections.

bash
Copy code
pip install gunicorn daphne
Step 5: Configure Environment Variables and Secrets

1. Environment Variables: Create an .env file or use environment variables to manage


sensitive information like API keys.

bash
Copy code
export DJANGO_SECRET_KEY="your-secret-key"
export OPENAI_API_KEY="your-openai-api-key"

2. Django Settings: Configure settings.py to read from environment variables, using


os.environ.get().

Step 6: Configure Django Channels

Set up Django Channels and define the ASGI_APPLICATION in settings.py.

python
Copy code
# settings.py
ASGI_APPLICATION = 'your_project_name.asgi.application'

CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [("127.0.0.1", 6379)],
},
},
}

Step 7: Set Up Redis for Django Channels

Install Redis, which Django Channels uses for managing WebSocket connections.

bash
Copy code
sudo apt install redis-server

Verify Redis is running by entering:

bash
Copy code
redis-cli ping

Step 8: Configure ASGI and WSGI

1. Configure asgi.py for Channels support:

python
Copy code
# asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import medical.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'your_project_name.settings')

application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
medical.routing.websocket_urlpatterns
)
),
})

2. Configure wsgi.py for regular HTTP requests.

Step 9: Set Up Gunicorn and Daphne

Use Gunicorn for HTTP requests and Daphne for WebSockets.

1. Create Gunicorn Service: Create a service file for Gunicorn to handle HTTP.

ini
Copy code
# /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=your_username
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/your/venv/bin/gunicorn --workers 3 --bind
unix:/path/to/your/project/gunicorn.sock
your_project_name.wsgi:application

[Install]
WantedBy=multi-user.target

2. Create Daphne Service: Create a service file for Daphne to handle WebSockets.

ini
Copy code
# /etc/systemd/system/daphne.service
[Unit]
Description=Daphne ASGI server
After=network.target
[Service]
User=your_username
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/your/venv/bin/daphne -b 0.0.0.0 -p 8001
your_project_name.asgi:application

[Install]
WantedBy=multi-user.target

3. Enable and Start Services:

bash
Copy code
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
sudo systemctl start daphne
sudo systemctl enable daphne

Step 10: Configure Nginx as a Reverse Proxy

Set up Nginx to route HTTP requests to Gunicorn and WebSocket connections to Daphne.

1. Create Nginx Configuration File:

conf
Copy code
# /etc/nginx/sites-available/your_project_name
server {
listen 80;
server_name your_domain_or_IP;

location / {
include proxy_params;
proxy_pass http://unix:/path/to/your/project/gunicorn.sock;
}

location /ws/ {
proxy_pass http://127.0.0.1:8001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}

location /static/ {
alias /path/to/your/staticfiles/;
}

location /media/ {
alias /path/to/your/mediafiles/;
}
}
2. Enable Nginx Configuration:

bash
Copy code
sudo ln -s /etc/nginx/sites-available/your_project_name
/etc/nginx/sites-enabled
sudo nginx -t # Test configuration
sudo systemctl restart nginx

Step 11: Configure HTTPS with Let’s Encrypt (Optional)

To secure your site with HTTPS:

bash
Copy code
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain

Step 12: Set Up Automated Deployment (Optional)

Use Git to push code changes to the server and deploy automatically.

1. Push Code to Server:


o Clone your repository on the server and pull changes when needed.
2. Restart Services on Update:
o Run sudo systemctl restart gunicorn daphne after deploying updates.

Final Steps

 Verify: Check the application by visiting the domain or IP in a web browser.


 Test WebSockets: Open multiple tabs to confirm that WebSocket connections are
handled correctly.

This deployment setup leverages Gunicorn for HTTP, Daphne for WebSockets, Redis for Django
Channels, and Nginx as a reverse proxy, allowing your Django project to handle HTTP and
WebSocket traffic efficiently in production. Let me know if you need further assistance!

4o
How ca

You might also like