Welcome to the backend of the Social Site Clone app. This Django-based repository offers a dynamic range of features, making it a robust solution for modern web applications.
- Django Rest Framework: Simplifies building Web APIs.
- JWT Authentication: Uses
rest_framework_simplejwt
for secure user authentication. - Real-time updates: Broadcasts likes and comments in real-time using
RedisChannelLayer
. - Background Tasks: Manages asynchronous tasks like HLS video conversion with
background_task
. - WhiteNoise: Efficiently serves static files.
- Daphne & ASGI: Provides enhanced performance and concurrency.
- Web Server: Django and Daphne.
- Database: PostgreSQL (with SQLite3 for testing).
- Real-time Operations: Redis.
- Static Files Management: WhiteNoise.
Ensure you have these environment variables set (preferably in a .env
file):
SECRET_KEY
: Your Django secret key.- For PostgreSQL:
DB_PASSWORD
,DB_HOST
,DB_PORT
.
-
Clone the repository:
git clone <repository-url> cd social-site-clone-backend
-
Install the required packages:
pip install -r requirements.txt
-
Set up the database (Ensure PostgreSQL is running if you're using it):
python manage.py migrate
-
Start the Daphne server:
daphne core.asgi:application
After following these steps, the Social Site Clone backend should be operational on your local setup. You can access it via the address and port specified by Daphne.
The project is currently configured to accept connections from all hosts.
ALLOWED_HOSTS: This setting is potentially insecure and should be adjusted before moving to a production environment.
CORS (Cross-Origin Resource Sharing) has been pre-configured for local testing scenarios and for a frontend hosted on Netlify. You may need to modify the CORS settings based on your specific production requirements.
- Limit
ALLOWED_HOSTS
to only the domains and subdomains that should serve the application. - Adjust CORS settings to whitelist specific origins, ensuring that only trusted sources can interact with your backend.
This document covers the core components of the user registration system for the Social Site Clone.
The Profile
model extends the default Django User
model, enhancing it with several additional fields:
- followers: A many-to-many relationship representing the user's followers, allowing a user to follow other users.
- username, firstname, lastname: Basic identity attributes of the user.
- bio: A short description or bio of the user.
- email: Email associated with the user.
- profile_picture & cover_image: Image fields for the user. If not provided, default images are set.
- created_at: Timestamp for when the profile was created.
Whenever a new user signs up, an associated Profile
instance is automatically created for them. This ensures that every user has a profile ready for additional information and customization.
Users can upload a custom image that becomes their profile picture. This is handled during the sign-up process, where an image can be passed along with other sign-up details. This feature provides users a way to personalize their profiles from the very start.
This serializer manages the Profile
model, converting it into JSON data for easy transmission and vice-versa. Every attribute of the Profile
model is serialized.
Handles the creation of a new user:
- Validates that the
email
andusername
are unique. - Uses Django's built-in utilities for password validation.
- Ensures proper creation of the user instance and setting of its password.
Django signals are utilized for automation:
- create_profile: Post the creation of a
User
instance, this signal triggers the creation of an associatedProfile
instance. - save_profile: Whenever a
User
instance is updated, this signal ensures the changes reflect in its linkedProfile
instance, or creates one if none exists.
A dedicated view for updating the user's images:
- Requires user authentication via JWT.
- Accepts new images for
profile_picture
andcover_image
in base64 format through POST requests. - Decodes and saves the provided images.
- Returns a success message and the updated user data upon successful execution.
This Django project allows users to upload media content in chunks, offering a more efficient and reliable system for large file uploads.
- Chunked Uploading: Divide large files into manageable chunks for easier uploads.
- File Finalization: After all chunks are uploaded, the server processes and merges them to re-form the original file.
- Stable for Unstable Connections: If an upload fails due to connection issues, you only need to re-upload the failed chunk, not the entire file.
-
Prepare the File:
- On the client side, divide your file into smaller chunks.
- Initiate an upload session using the
PostCreateAPIView
.
-
Upload the Chunks:
- For images, use the
PostImageCreateAPIView
. - For videos, use the
PostVideoCreateAPIView
. - Send chunks one by one to the respective endpoint.
- For images, use the
-
Finalize the Upload:
- Once all chunks are uploaded, signal the server to concatenate the chunks and finalize the media file using
FinalizeUploadView
.
- Once all chunks are uploaded, signal the server to concatenate the chunks and finalize the media file using
- Create Post:
post/create/
- Add Image Chunk:
post/add/media/image/
- Add Video Chunk:
post/add/media/video/
- Finalize Video:
post/add/media/video/finalize/
In this Django application, I've integrated state-of-the-art video processing capabilities, harnessing the potential of HTTP Live Streaming (HLS) to deliver an optimized video streaming experience.
HLS, short for HTTP Live Streaming, is a streaming protocol pioneered by Apple. It's designed to deliver media content, primarily video, over the internet. The core principle behind HLS is segmenting a video file into smaller chunks and creating a playlist for these chunks, ensuring smooth playback across diverse network conditions.
-
MediaFile Model:
- Reference: The foundation is the
MediaFile
model (MediaFile(models.Model)
), where I store video files uploaded by users. - Chunked Uploads: Through the
append_chunk
method in theMediaFile
model, I've enabled chunked uploads. This approach ensures that segments of video data can be sent independently, and then the system assembles them in sequence.
- Reference: The foundation is the
-
Triggering HLS Encoding:
- After a video is completely uploaded, the
start_encoding
method in theMediaFile
model triggers the HLS encoding process. By running this process in the background, the main application remains seamless and user-friendly.
- After a video is completely uploaded, the
-
Utilizing FFmpeg:
- Reference: My
encode_video_to_hls
function taps into FFmpeg for the video conversion. - FFmpeg plays a key role in segmenting the video into varying resolutions (like 360p, 720p). This ensures adaptive playback, catering to different devices and internet speeds.
- Reference: My
-
Structured Storage:
- The segmented video chunks, along with their master playlist, are organized in a directory (evident from
os.path.join(settings.MEDIA_ROOT, 'hls', str(mediafile.id))
). This neat arrangement ensures swift access during streaming.
- The segmented video chunks, along with their master playlist, are organized in a directory (evident from
-
Adaptive Streaming Experience:
- During playback, the HLS protocol combined with my backend ensures viewers receive the optimal video quality according to their network. Should there be any fluctuation, HLS adjusts accordingly, promising a smooth viewing experience.
- Uninterrupted Streaming: Thanks to HLS, viewers experience minimal buffering, even in fluctuating network scenarios.
- Optimal Quality: My system ensures the best possible video quality for every user.
- Universal Playback: Whether on mobile devices, desktops, or smart TVs, my solution promises top-notch video streaming.