Django
Django (https://www.djangoproject.com/) is a powerful Python Web framework that follows the "Batteries-included" philosophy, providing an out-of-the-box full-stack solution. Renowned for efficient development, security, and stability, it features built-in modules like ORM, Admin backend, and user authentication, significantly reducing repetitive code. Django employs a clear MVC (MTV) architecture, supports high scalability, and is suitable for development ranging from rapid prototyping to enterprise-level applications.
This guide describes how to deploy a Django application on CloudBase HTTP cloud functions.
Prerequisites
Before you begin, make sure you have:
- Have Python 3.10 or later versions installed
- Have a Tencent Cloud account with CloudBase service activated
- Have basic knowledge of Python and Django development
Step 1: Create a Django Application
💡 Tip: If you already have a Django application, you can skip this step.
Set Up the Development Environment
Create a project directory and set up a virtual environment:
# Create a Project Directory
mkdir django-cloudbase
cd django-cloudbase
# Create a Virtual Environment
python -m venv env
# Activate the Virtual Environment
# Linux/macOS
source env/bin/activate
# Windows
# env\Scripts\activate
Install Django
python -m pip install django
Create a Django Project
django-admin startproject django_app .
This command will create a Django project named django_app in the current directory.
Configure Django Settings
Edit the django_app/settings.py file and add the necessary configurations for CloudBase cloud functions:
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', 'your-secret-key-here')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', 'False').lower() == 'true'
ALLOWED_HOSTS = ['*'] # Allow access from all hosts
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Create a Simple View
Edit the django_app/urls.py file:
from django.contrib import admin
from django.urls import path
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
def home(request):
"""Home View"""
return JsonResponse({
'message': 'Hello from Django on CloudBase!',
'method': request.method,
'path': request.path
})
def health(request):
"""Health Check API"""
return JsonResponse({
'status': 'healthy',
'framework': 'Django',
'version': '4.2'
})
@csrf_exempt
def api_info(request):
"""API Information Interface"""
data = {
'method': request.method,
'path': request.path,
'headers': dict(request.headers),
'get_params': dict(request.GET),
}
if request.method == 'POST':
try:
data['post_data'] = json.loads(request.body) if request.body else {}
except json.JSONDecodeError:
data['post_data'] = request.POST.dict()
return JsonResponse(data)
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home'),
path('health/', health, name='health'),
path('api/info/', api_info, name='api_info'),
]
Step 2: Test Locally
Test the application locally before deployment:
⚠️ Important Notice: CloudBase HTTP cloud function requires the application to listen on port 9000.
# Run Database Migration
python manage.py migrate
# Start Up the Development Server (Using Port 9000)
python manage.py runserver 0.0.0.0:9000
Open your browser and access http://127.0.0.1:9000. You should see a JSON response.
Test other APIs:
http://127.0.0.1:9000/health- Health Checkhttp://127.0.0.1:9000/api/info/- API Information
Step 3: Configure Dependencies
Generate the requirements.txt file:
pip freeze > requirements.txt
⚠️ Note: It is only safe to run the above command in a virtual environment. Otherwise, it will generate all installed Python packages on the system, which may prevent the cloud function from starting up properly.
Typical requirements.txt contents:
asgiref==3.7.2
Django==4.2.7
sqlparse==0.4.4
tzdata==2023.3
Step 4: Create a Startup Script
Create the scf_bootstrap file (without extension):
#!/bin/bash
export PYTHONPATH="./env/lib/python3.10/site-packages:$PYTHONPATH"
# Run Database Migration
/var/lang/python310/bin/python3.10 manage.py migrate --noinput
# Collect Static Files
/var/lang/python310/bin/python3.10 manage.py collectstatic --noinput
# Start Up the Django Application
/var/lang/python310/bin/python3.10 manage.py runserver 0.0.0.0:9000
Grant execute permission to the startup script:
chmod +x scf_bootstrap
💡 Note:
scf_bootstrapis the startup script for CloudBase cloud functions- The script will automatically run database migration and collect static files.
- Ensure the application listens on port 9000
Step 5: Prepare Deployment Files
Ensure your project directory structure is as follows:
django-cloudbase/
├── env/ # Virtual Environment
├── django_app/ # Django Project Directory
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py # Django Management Script
├── requirements.txt # Dependency List
├── scf_bootstrap # Startup script
└── db.sqlite3 # Database file (optional)
Step 6: Deploy to CloudBase HTTP Cloud Function
Deploy via the Console
- Log in to the CloudBase Console
- Select your environment and go to the [Cloud Function] page
- Click [New Cloud Function]
- Select [HTTP cloud function]
- Fill in the function name (for example:
django-app) - Select runtime: Python 3.10
- Select submission method: Local folder upload
- Select the project root directory for function code upload
- Automatic Dependency Installation: Enable this option
- Click the "Create" button and wait for the deployment to complete.
Deploy via CLI (Coming Soon)
Package and deploy
If you need to package manually:
# Create Deployment Package
zip -r django-app.zip . -x "*.git*" "*__pycache__*" "*.pyc"
Step 7: Access Your Application
After successful deployment, you can refer to Accessing Cloud Functions via HTTP to configure custom domain access for
You can test the following APIs:
- Root Path: View welcome message
/health/: Check health status/api/info/: View request information/admin/: Access the Django admin site
Frequently Asked Questions
Q: Why must I use port 9000?
A: The CloudBase HTTP cloud function requires the application to listen on port 9000, which is the standard configuration of the platform.
Q: How do I handle static files?
A: Configure STATIC_ROOT in settings.py and run the collectstatic command in scf_bootstrap.
Q: How do I set up the database?
A: For production environments, it is recommended to use CloudBase database or other cloud database services rather than SQLite.
Q: How do I view application logs?
A: On the CloudBase console's cloud function page, click the function name to go to the details page and view the running logs.
Q: How to manage Django's SECRET_KEY?
A: It is recommended to manage sensitive configurations using environment variables and set them in cloud functions.
Best Practices
- Environment Variable Management: Use environment variables to manage sensitive configuration information.
- Database Selection: Use cloud database rather than SQLite for production environments.
- Static File Handling: Ensure proper configuration for static file collection and serving.
- Security Configuration: Disable DEBUG mode in production environments.
- Logging: Configure appropriate log level and output format.
- Error Handling: Implement global exception handling and user-friendly error pages
Advanced Configuration
Use a WSGI server
For production environments, it is recommended to use a WSGI server such as Gunicorn:
# Install Gunicorn
pip install gunicorn
# Update requirements.txt
pip freeze > requirements.txt
Modify scf_bootstrap:
#!/bin/bash
export PYTHONPATH="./env/lib/python3.10/site-packages:$PYTHONPATH"
# Run Migration
/var/lang/python310/bin/python3.10 manage.py migrate --noinput
# Collect Static Files
/var/lang/python310/bin/python3.10 manage.py collectstatic --noinput
# Starting with Gunicorn
/var/lang/python310/bin/python3.10 -m gunicorn django_app.wsgi:application --bind 0.0.0.0:9000
Environment Variable Configuration
Set environment variables in the cloud function console:
SECRET_KEY: Django secret keyDEBUG: Debug mode (False)DATABASE_URL: Database connection string (if using an external database)
Next Steps
- Learn more about HTTP cloud function configuration options
- Learn how to connect to the CloudBase database