Django
Django is a powerful Python Web framework that follows the "Batteries-included" philosophy, delivering 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 with high scalability, suitable for development ranging from rapid prototyping to enterprise-level applications.
This guide describes how to deploy Django applications on CloudBase HTTP cloud functions.
Prerequisites
Before you begin, ensure that you have:
- Installed Python 3.10 or a later version
- Have a Tencent Cloud account and have activated the CloudBase service
- Have a basic knowledge of Python and Django development
Step 1: Create a Django Application
💡 Note: 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 the 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 all hosts to access
# 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': ':memory:',
}
}
# 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 Page View"""
return JsonResponse({
'message': 'Hello from Django on CloudBase!',
'method': request.method,
'path': request.path
})
def health(request):
"""Health Check Endpoint"""
return JsonResponse({
'status': 'healthy',
'framework': 'Django',
'version': '4.2'
})
@csrf_exempt
def api_info(request):
"""API Information Endpoint"""
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: Local Testing
Before deployment, test the application locally first:
⚠️ Important: CloudBase HTTP cloud functions require the application to listen on port 9000.
# Run Database Migrations
python manage.py migrate
# Start the Development Server (using port 9000)
python manage.py runserver 0.0.0.0:9000
Open your browser and visit http://127.0.0.1:9000, you should see a JSON response.
Test other endpoints:
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 cause the cloud function to fail to start up properly.
Typical requirements.txt contents:
# Django 4.2 LTS - Compatible with SQLite 3.26+, cloud function default runtime has SQLite version requirements
Django==4.2.16
asgiref==3.7.2
psycopg2-binary==2.9.11
sqlparse==0.4.4
typing_extensions==4.15.0
Step 4: Create the Startup Script
💡 Note:
- When creating the
scf_bootstrapfile on windows, it is recommended to use- When creating the
scf_bootstrapfile using vscode on windows, deploying to an HTTP cloud function may result in an error:scf_bootstrapfile does not exist- This error occurs because the script file contains Windows-style carriage returns (^M), causing Linux to fail to recognize the interpreter path correctly. This is a common issue in WSL
Create the scf_bootstrap file (with no extension):
#!/bin/bash
# Set the Python dependency loading path, which defaults to the third_party directory
export PYTHONPATH="./third_party:$PYTHONPATH"
# Run Database Migrations
/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 permissions to the startup script:
chmod +x scf_bootstrap
💡 Note:
scf_bootstrapis the startup script for CloudBase cloud functions- The script will automatically run database migrations and collect static files.
- Ensure the application listens on port 9000
Step 5: Prepare Deployment Files
Before deployment, install dependencies to the third_party directory:
⚠️ Note:
- HTTP cloud functions do not automatically install Python dependencies, so we need to manually download them into the code package
pip install -r requirements.txt -t third_party
Ensure your project directory structure is as follows:
django-cloudbase/
├── third_party/ # Third-party dependencies
├── django_app/ # Django project directory
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py # Django management script
├── requirements.txt # Dependencies list
├── scf_bootstrap # Startup script
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 (such as:
django-app) - Select runtime: Python 3.10
- Select submit method: Local folder upload
- Select the project root directory to upload the function code
- Automatic dependency installation: Enable this option
- Click the "Create" button and wait for deployment to complete
Deploy via CLI
For details, see Deploy HTTP cloud function
Package and deploy
If you need to package manually:
# Create deployment package
zip -r django-app.zip third_party django_app manage.py scf_bootstrap
Step 7: Access Your Application
After successful deployment, you can refer to Accessing Cloud Functions via HTTP to set up custom domain access to the
You can test the following endpoints:
- Root path: View welcome message
/health/: Check health status/api/info/: View request information/admin/: Access the Django admin interface
Frequently Asked Questions
Q: Why must port 9000 be used?
A: CloudBase HTTP cloud functions require the application to listen on port 9000, which is the standard configuration of the platform.
Q: How to handle static files?
A: Configure STATIC_ROOT in settings.py and run the collectstatic command in scf_bootstrap.
Q: How to configure the database?
A: For production environments, it is recommended to use CloudBase database or other cloud database services rather than SQLite.
Q: How to view application logs?
A: On the Cloud Functions page of the CloudBase console, click the function name to go to the details page and view the runtime logs.
Q: How to manage Django's SECRET_KEY?
A: It is recommended to use environment variables to manage sensitive configurations 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: Properly configure the collection and serving of static files.
- Security Configuration: Disable DEBUG mode in production environments.
- Logging: Configure appropriate log level and output format.
- Error Handling: Implement global exception handling and friendly error pages.
Advanced Configuration
Using a WSGI Server
For production environments, it is recommended to use a WSGI server such as Gunicorn:
# Installing Gunicorn
pip install gunicorn
# Updating requirements.txt
pip freeze > requirements.txt
Modify scf_bootstrap:
#!/bin/bash
export PYTHONPATH="./env/lib/python3.10/site-packages:$PYTHONPATH"
# Run Migrations
/var/lang/python310/bin/python3.10 manage.py migrate --noinput
# Collect Static Files
/var/lang/python310/bin/python3.10 manage.py collectstatic --noinput
# Start using Gunicorn
/var/lang/python310/bin/python3.10 -m gunicorn django_app.wsgi:application --bind 0.0.0.0:9000
Environment Variable Configuration
Setting 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 CloudBase database