Skip to content

Latest commit

 

History

History
338 lines (275 loc) · 9.66 KB

File metadata and controls

338 lines (275 loc) · 9.66 KB

Social Media Backend Application

#Shriyam's Project- Comments(posting and replying)- text and multimedia

A Flask-based microservices backend application for a social media platform, featuring user management, posts, and comments functionality.

Prerequisites

Before starting, you'll need to install these tools:

1. Visual Studio Code

2. Python

3. MySQL

4. Postman

Project Setup

1. Download and Extract Project

  1. Download the project zip file
  2. Extract to your preferred location
  3. Open the folder in VS Code:
    • File → Open Folder → Select the extracted folder

2. Set Up Python Virtual Environment

Open VS Code terminal (Terminal → New Terminal) and run:

For Windows:

python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt

For Mac/Linux:

python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt

3. Database Setup

  1. Open MySQL Workbench
  2. Connect to your local MySQL server
  3. Create the database:
CREATE DATABASE social_media_app_bd1;

4. Configure Database Connection

Update database configuration in these files with your MySQL password:

  • user_app/app.py
  • post_app/app.py

Change this line in both files:

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:YOUR_PASSWORD@localhost/social_media_app_bd1'#your passwords to mysql should not contain any special character like @,#,$ etc, it doesn't seem to read those so keep it simple

Running the Application

Method 1: Using app_runner.py (Recommended)

  1. Ensure your virtual environment is activated
  2. Run:
python app_runner.py  # Use python3 on Mac/Linux- can throw error sometimes

Method 2: Running Services Separately

  1. First Terminal (User Service):
python user_app/app.py  # Use python3 on Mac/Linux
  1. Second Terminal (Post Service):
python post_app/app.py  # Use python3 on Mac/Linux

Testing the APIs

1. Create a User

POST http://localhost:5001/api/users
Content-Type: application/json

{
    "username": "testuser",
    "email": "test@example.com",
    "password": "password123",
    "full_name": "Test User",
    "bio": "Hello World!"
}

2. Create a Post

POST http://localhost:5002/api/posts
Content-Type: application/json

{
    "user_id": 1,
    "content": "This is my first post!"
}

3. Add a Comment

POST http://localhost:5002/api/posts/1/comments
Content-Type: application/json

{
    "user_id": 1,
    "content": "This is a comment!",
    "media_url": "https://example.com/image.jpg"
}

4. View Posts and Comments

  • Get all posts: GET http://localhost:5002/api/posts
  • Get post comments: GET http://localhost:5002/api/posts/1/comments
  • Get users: GET http://localhost:5001/api/users

Project Structure

social_media_app/
├── shared/
│   ├── models/
│   │   ├── user_model.py
│   │   └── post_model.py
│   └── utils/
│       └── db_utils.py
├── user_app/
│   ├── routes/
│   ├── controllers/
│   ├── services/
│   └── app.py
└── post_app/
    ├── routes/
    ├── controllers/
    ├── services/
    └── app.py

Troubleshooting

Common Issues and Solutions

  1. Database Connection Error

    • Verify MySQL is running
    • Check password in configuration files
    • Ensure database exists
  2. Port Already in Use

    • Check if any other application is using ports 5001/5002
    • Close other Python processes
    • Restart your computer if needed
  3. Package Installation Issues

    • Ensure virtual environment is activated
    • Try: pip install --upgrade pip
    • Install packages individually if needed
  4. Python Path Issues

    • Verify Python is added to PATH
    • Restart VS Code after installation
    • Use full paths if needed

Additional Resources

Code Implementation

1. Update Post Model

In shared/models/post_model.py:

from datetime import datetime
from shared.utils.db_utils import db

class Post(db.Model):
    __tablename__ = 'posts'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, nullable=False)
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    comments = db.relationship('Comment', backref='post', lazy=True)

class Comment(db.Model):
    __tablename__ = 'comments'
    
    id = db.Column(db.Integer, primary_key=True)
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable=False)
    user_id = db.Column(db.Integer, nullable=False)
    content = db.Column(db.Text, nullable=False)
    media_url = db.Column(db.String(255))
    parent_comment_id = db.Column(db.Integer, db.ForeignKey('comments.id'))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # For handling nested replies
    replies = db.relationship('Comment', backref=db.backref('parent', remote_side=[id]))

2. Create Comment Controller

In post_app/controllers/comment_controller.py:

from flask import jsonify, request
from shared.models.post_model import Comment, Post
from shared.utils.db_utils import db

def create_comment(post_id):
    try:
        data = request.get_json()
        new_comment = Comment(
            post_id=post_id,
            user_id=data['user_id'],
            content=data['content'],
            media_url=data.get('media_url'),
            parent_comment_id=data.get('parent_comment_id')
        )
        db.session.add(new_comment)
        db.session.commit()
        return jsonify({'message': 'Comment created successfully', 'comment_id': new_comment.id}), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400

def get_post_comments(post_id):
    try:
        comments = Comment.query.filter_by(post_id=post_id, parent_comment_id=None).all()
        comments_data = []
        for comment in comments:
            comment_dict = {
                'id': comment.id,
                'user_id': comment.user_id,
                'content': comment.content,
                'media_url': comment.media_url,
                'created_at': comment.created_at.isoformat(),
                'replies': get_comment_replies(comment.id)
            }
            comments_data.append(comment_dict)
        return jsonify(comments_data), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400

def get_comment_replies(comment_id):
    replies = Comment.query.filter_by(parent_comment_id=comment_id).all()
    replies_data = []
    for reply in replies:
        reply_dict = {
            'id': reply.id,
            'user_id': reply.user_id,
            'content': reply.content,
            'media_url': reply.media_url,
            'created_at': reply.created_at.isoformat()
        }
        replies_data.append(reply_dict)
    return replies_data

3. Add Comment Routes

In post_app/routes/comment_routes.py:

from flask import Blueprint
from post_app.controllers.comment_controller import create_comment, get_post_comments

comment_bp = Blueprint('comment', __name__)

@comment_bp.route('/posts/<int:post_id>/comments', methods=['POST'])
def add_comment(post_id):
    return create_comment(post_id)

@comment_bp.route('/posts/<int:post_id>/comments', methods=['GET'])
def list_comments(post_id):
    return get_post_comments(post_id)

###4. Update services in post_App In post_app/services/post_service.py, add:

    @staticmethod
    def add_comment(user_id, post_id, content, parent_id=None, media_url=None):
        comment = Comment(
            user_id=user_id,
            post_id=post_id,
            content=content,
            parent_id=parent_id,
            media_url=media_url
        )

5. Update Post App

In post_app/app.py, add:

from post_app.routes.comment_routes import comment_bp

# ... existing code ...
app.register_blueprint(comment_bp, url_prefix='/api')

Support

If you encounter any issues:

  1. Check the error message carefully
  2. Verify all installation steps
  3. Ensure all services are running
  4. Try restarting your computer
  5. do not worry if you don't get it in first try ,we ourselves did this in 2 months , so just go easy on yourself and keep trying.

#THANK_YOU