tencent cloud

Cloud Object Storage

Release Notes and Announcements
Release Notes
Announcements
Product Introduction
Overview
Features
Use Cases
Strengths
Concepts
Regions and Access Endpoints
Specifications and Limits
Service Regions and Service Providers
Billing
Billing Overview
Billing Method
Billable Items
Free Tier
Billing Examples
Viewing and Downloading Bill
Payment Overdue
FAQs
Getting Started
Console
Getting Started with COSBrowser
User Guide
Creating Request
Bucket
Object
Data Management
Batch Operation
Global Acceleration
Monitoring and Alarms
Operations Center
Data Processing
Content Moderation
Smart Toolbox
Data Processing Workflow
Application Integration
User Tools
Tool Overview
Installation and Configuration of Environment
COSBrowser
COSCLI (Beta)
COSCMD
COS Migration
FTP Server
Hadoop
COSDistCp
HDFS TO COS
GooseFS-Lite
Online Tools
Diagnostic Tool
Use Cases
Overview
Access Control and Permission Management
Performance Optimization
Accessing COS with AWS S3 SDK
Data Disaster Recovery and Backup
Domain Name Management Practice
Image Processing
Audio/Video Practices
Workflow
Direct Data Upload
Content Moderation
Data Security
Data Verification
Big Data Practice
COS Cost Optimization Solutions
Using COS in the Third-party Applications
Migration Guide
Migrating Local Data to COS
Migrating Data from Third-Party Cloud Storage Service to COS
Migrating Data from URL to COS
Migrating Data Within COS
Migrating Data Between HDFS and COS
Data Lake Storage
Cloud Native Datalake Storage
Metadata Accelerator
GooseFS
Data Processing
Data Processing Overview
Image Processing
Media Processing
Content Moderation
File Processing Service
File Preview
Troubleshooting
Obtaining RequestId
Slow Upload over Public Network
403 Error for COS Access
Resource Access Error
POST Object Common Exceptions
API Documentation
Introduction
Common Request Headers
Common Response Headers
Error Codes
Request Signature
Action List
Service APIs
Bucket APIs
Object APIs
Batch Operation APIs
Data Processing APIs
Job and Workflow
Content Moderation APIs
Cloud Antivirus API
SDK Documentation
SDK Overview
Preparations
Android SDK
C SDK
C++ SDK
.NET(C#) SDK
Flutter SDK
Go SDK
iOS SDK
Java SDK
JavaScript SDK
Node.js SDK
PHP SDK
Python SDK
React Native SDK
Mini Program SDK
Error Codes
Harmony SDK
Endpoint SDK Quality Optimization
Security and Compliance
Data Disaster Recovery
Data Security
Cloud Access Management
FAQs
Popular Questions
General
Billing
Domain Name Compliance Issues
Bucket Configuration
Domain Names and CDN
Object Operations
Logging and Monitoring
Permission Management
Data Processing
Data Security
Pre-signed URL Issues
SDKs
Tools
APIs
Agreements
Service Level Agreement
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary
DokumentasiCloud Object StorageUse CasesUsing COS in the Third-party ApplicationsImplementing a Cloud Storage Solution for Web Applications Using Django + COS

Implementing a Cloud Storage Solution for Web Applications Using Django + COS

PDF
Mode fokus
Ukuran font
Terakhir diperbarui: 2025-12-24 11:00:45

Introduction

Django is an open-source Python-based Web application framework that significantly simplifies the development process of Web applications. To better meet the demands of modern Web applications, Django provides numerous extension features, including cloud storage.
This article mainly introduces how to use the COS plugin to implement the remote attachment feature, storing data of Django applications on Tencent Cloud COS (Cloud Object Storage, COS).

Prerequisites

If you do not have a COS bucket, refer to the Create Bucket operation guide.
A server has been created, such as Cloud Virtual Machine (CVM). For related guidance, refer to the CVM product documentation.

Environment Dependency

Python version: greater than or equal to version 3.8. This article uses Python version 3.12.0 as an example.
COS Python version: greater than or equal to version 1.9.31. For installation methods, see COS Python SDK Quick Start. This article uses COS Python version 1.9.31 as an example.
Django version: greater than or equal to 2.2 and less than 3.3. This article uses version 3.2.18 as an example.

Practical Steps

Create a COS Bucket

1. Create a bucket with access permission set to public-read-private-write. It is recommended that the bucket region matches the region of the CVM running Django. For creation details, see the Create Bucket documentation.
2. Locate the newly created bucket in the bucket list and obtain the bucket name, for example, examplebucket-1250000000.

Create Django

1. Go to the PyCharm official website and select the corresponding PyCharm version based on the operating system of your CVM.
2. After PyCharm is installed on the CVM, open it, click NEW project or create project, and select Django below.

3. After creation, locate and open the setting.py file in your directory.



4. Copy and paste the following code into it and configure the COS service according to the parameter description.
DEFAULT_FILE_STORAGE = "django_cos_storage.TencentCOSStorage"

TENCENTCOS_STORAGE = {
"BUCKET": "xxx",
"CONFIG": {
"Region": "ap-guangzhou",
"SecretId": "xxxx",
"SecretKey": "xxxx",
}
}
The parameter description is as follows:
Configuration Item
Configuration Value
Bucket
The custom name defined when a bucket is created, for example, examplebucket-1250000000.
Region
The region selected when the bucket was created.
SecretId
Access key information can be created and obtained in TencentCloud API Keys. It is recommended to use sub-account keys and follow the principle of least privilege to mitigate usage risks. For details, see Access Key Management for Sub-accounts.
SecretKey
Access key information can be created and obtained in TencentCloud API Keys. It is recommended to use sub-account keys and follow the principle of least privilege to mitigate usage risks. For details, see Sub-account Access Key Management.

Download and Configure the COS Plugin

1. Go to Github to download the COS plugin. After downloading it, extract the django_cos_storage directory to the directory of your django project.
Note:
To view its plugin information, open the terminal, enter pip freeze, then you can view its module information.
2. Create a Python file, for example, COSStorage.py, in the django_cos_storage directory.



Copy and paste the following code into it.
from .storage import TencentCOSStorage
from functools import wraps

def decorator(cls):

instance = None
@wraps(cls)
def inner(*args,**kwargs):
nonlocal instance
if not instance:
instance = cls(*args,**kwargs)
return instance
return inner

@decorator
class QFStorage:
def __init__(self):
pass
self.storage =TencentCOSStorage()
self.bucket =self.storage.bucket
self.client =self.storage.client

#Upload Object
def upload_file(self, Key, LocalFilePath, PartSize=1, MAXThread=5, EnableMD5=False):
try:
response =self.client.upload_file(
Bucket=self.bucket,
Key=Key,
LocalFilePath=LocalFilePath,
PartSize=PartSize,
MAXThread=MAXThread,
EnableMD5=EnableMD5
)
return response
except Exception as e:
print('Failed to upload object, error:', e)
return None
3. Open views.py in the app_cos directory.



Copy and paste the following code into it.
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django_cos_storage.COSStorage import QFStorage
from django.conf import settings


#Upload Object

def upload_file_view(request):
response = QFStorage().upload_file(
Key='1.png',
LocalFilePath=settings.BASE_DIR / 'cessu/1.png'
)

if response:
return HttpResponse('File uploaded successfully!')
return HttpResponse('File upload failed')
Note:
In this example, cessu/1.png represents the local file to be uploaded, 1.png is located in the cessu folder under the project directory. After successful upload, you can find the image 1.png in the cessu folder of the COS bucket.
4. Find and open urls.py in the djangoProject2 directory.

Copy and paste the code into it.
from django.contrib import admin
from django.urls import path
from app_cos.views import *

urlpatterns = [
path('admin/', admin.site.urls),

path('upload_file/', upload_file_view),
]
5. Enter python manage.py migrate in the terminal and run it.
6. Enter python manage.py createsuperuser in the terminal and follow the prompts to enter your username and password.
Note:
If executing python manage.py createsuperuser prompts that pkg_resources is missing, please execute the installation command pip install setuptools to resolve it.



7. Then, run python .\\manage.py runserver in the terminal.

8. Open the website http://127.0.0.1:8000/admin/ and enter the previously set username and password to log in.



Note:
If opening the website displays the following error:

Return to pycharm, reopen the terminal, and enter the following commands in sequence:
python manage.py makemigrations
python manage.py migrate

Finally, run python .\\manage.py runserver in the terminal, then open http://127.0.0.1:8000/admin/.

Verifying storage of Django attachments to COS

1. Access http://127.0.0.1:8000/upload_file to complete the operation to upload files. When the prompt as shown below is displayed, it indicates a successful upload.



2. Log in to the COS console, select the previously created bucket, and under the cessu path, you can see the uploaded images.

Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan