@app.route('/video/int:video_id', methods=['GET', 'POST'])
def video(video_id):
current_video = db_sess.query(Video).get(video_id)
if current_video is None:
return page_not_found('')
code
Assistant
# Проверяем, разрешены ли комментарии для этого видео
comments_enabled = current_video.comments_enabled
# Получаем автора видео
author = current_video.author
all_videos = db_sess.query(Video).all()
# Проверяем, поставил ли текущий пользователь лайк и подписан ли
like = False
subscription = False
# Check if the user is logged in
if current_user.is_authenticated:
# Check if the user has already viewed the video
view_exists = db_sess.query(VideoView).filter_by(
user_id=current_user.id, video_id=video_id).first()
# If not, increment the view count and add a record to video_views
if not view_exists:
current_video.views += 1
new_view = VideoView(user_id=current_user.id, video_id=video_id)
db_sess.add(new_view)
db_sess.commit()
if current_user.is_authenticated:
likes = json.loads(current_user.likes)
subscriptions = json.loads(current_user.subscriptions)
if video_id in likes:
like = True
if current_video.author in subscriptions:
subscription = True
# Обрабатываем форму комментария
# Обрабатываем форму комментария только если комментарии включены
form = CommentForm()
if comments_enabled and form.validate_on_submit():
if current_user.is_authenticated and not current_user.is_blocked:
# Добавление комментария
comment = Comment(
content=form.content.data,
user_id=current_user.id,
video_id=video_id,
parent_id=form.parent_id.data or None
)
db_sess.add(comment)
db_sess.commit()
flash('Комментарий добавлен!', 'success')
return redirect(url_for('video', video_id=video_id))
else:
flash('Вы не можете оставить комментарий.', 'danger')
return redirect
# Получаем комментарии к видео
comments = db_sess.query(Comment).filter(Comment.video_id == video_id).options(
joinedload(Comment.user),
joinedload(Comment.parent).joinedload(Comment.user),
joinedload(Comment.replies).joinedload(Comment.user)
).order_by(Comment.datetime.desc()).all() # Изменено на desc() для сортировки в обратном порядке
# Создаем словарь комментариев по id для удобства доступа
comments_by_id = {comment.id: comment for comment in comments}
# Строим дерево комментариев
root_comments = []
for comment in comments:
if comment.parent_id is None:
root_comments.append(comment)
else:
parent = comments_by_id.get(comment.parent_id)
if parent:
if not hasattr(parent, 'replies_sorted'):
parent.replies_sorted = []
parent.replies_sorted.append(comment)
last_videos = all_videos[len(all_videos) - 10:][::-1]
params = {
'title': f"{current_video.title} - {author.name} {author.surname}",
'current_video': current_video,
'video_src': url_for("static", filename=f'vid/{video_id}.mp4'),
'author': author,
'like': like,
'subscription': subscription,
'db_sess': db_sess,
'comments': root_comments,
'User': User,
'authenticated': current_user.is_authenticated,
'current_user': current_user,
'avatar_url': url_for('static', filename=f'avatars/{author.avatar}'),
'comments': comments,
'last_videos': last_videos,
'form': form
}
return render_template('video.html', **params)
data/videos.py
import sqlalchemy
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Boolean
from sqlalchemy.orm import relationship
from data.db_session import SqlAlchemyBase
from sqlalchemy_serializer import SerializerMixin
from datetime import datetime
class Video(SqlAlchemyBase, SerializerMixin):
tablename = 'videos'
code
id = Column(Integer, primary_key=True, unique=True, autoincrement=True, nullable=False)
title = Column(String, nullable=False)
author_id = Column(Integer, ForeignKey("users.id"), nullable=False)
description = Column(String, nullable=False, default='')
likes = Column(Integer, nullable=False, default=0)
datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
comments_enabled = Column(Boolean, default=True) # Новое поле
privacy = Column(Integer, nullable=False, default=3) # New field for privacy setting
comments = relationship('Comment', back_populates='video', cascade='all, delete-orphan')
author = relationship('User', back_populates='videos')
views = sqlalchemy.Column(sqlalchemy.Integer, nullable=False, default=0) # New field for view count
Your Flask route and Video model are quite comprehensive and handle multiple functionalities such as viewing videos, tracking views, managing likes and subscriptions, and handling comments. Below is a detailed review highlighting potential issues, optimizations, and best practices to enhance your code:
1. Handling Redirects Properly
Issue:
In the comment handling section, the return redirect statement lacks a target URL, which will raise an error.
python
else:
flash('Вы не можете оставить комментарий.', 'danger')
return redirect # Missing URL argument
Solution:
Specify a URL to redirect the user to. Typically, you might want to redirect them back to the same video page.
python
else:
flash('Вы не можете оставить комментарий.', 'danger')
return redirect(url_for('video', video_id=video_id))
2. Duplicate Dictionary Keys
Issue:
In the params dictionary, the key 'comments' is assigned twice, which means the first assignment (root_comments) is overwritten by the second (comments).
This approach reduces memory usage and improves performance.
4. Optimizing View Counting
Issue:
The current logic checks if a view exists and then increments the view count and adds a VideoView entry. This can lead to race conditions in high-concurrency scenarios.
python
if not view_exists:
current_video.views += 1
new_view = VideoView(user_id=current_user.id, video_id=video_id)
db_sess.add(new_view)
db_sess.commit()
Solution:
Consider using database-level transactions or locks to ensure atomicity. Alternatively, you might use a separate service or background task to handle view counts.
python
from sqlalchemy.exc import IntegrityError
try:
new_view = VideoView(user_id=current_user.id, video_id=video_id)
db_sess.add(new_view)
current_video.views += 1
db_sess.commit()
except IntegrityError:
db_sess.rollback()
# View already exists; do nothing or handle accordingly
Ensure that the VideoView table has a unique constraint on (user_id, video_id) to prevent duplicate views.
5. Improving JSON Field Usage for Likes and Subscriptions
Issue:
Storing likes and subscriptions as JSON fields in the User model can make querying inefficient and complicate data integrity.
class Video(SqlAlchemyBase, SerializerMixin):
__tablename__ = 'videos'
# ... other fields ...
liked_by = relationship('User', secondary=user_likes, back_populates='liked_videos')
This structure facilitates efficient queries like checking if a user liked a video or managing subscriptions.
6. Enhancing Comment Retrieval and Tree Building
Issue:
Manual tree building for comments can become complex and hard to maintain.
python
# Building comment tree manually
root_comments = []
for comment in comments:
if comment.parent_id is None:
root_comments.append(comment)
else:
parent = comments_by_id.get(comment.parent_id)
if parent:
if not hasattr(parent, 'replies_sorted'):
parent.replies_sorted = []
parent.replies_sorted.append(comment)
Solution:
Consider using a recursive function or utilizing existing libraries to handle hierarchical data. Alternatively, leverage SQLAlchemy's relationship loading with foreign_keys and remote_side for self-referential relationships.
comments = db_sess.query(Comment).filter(Comment.video_id == video_id).options(
joinedload(Comment.user),
joinedload(Comment.replies).joinedload(Comment.user)
).order_by(Comment.datetime.desc()).all()
# The `replies` relationship can be accessed directly in the template
root_comments = [comment for comment in comments if comment.parent_id is None]
This approach simplifies the comment tree management and leverages SQLAlchemy's capabilities.
7. Reducing Redundant Database Queries
Issue:
Multiple if current_user.is_authenticated: checks lead to redundant code and potential performance issues.
Solution:
Consolidate authentication checks to minimize redundancy.
python
if current_user.is_authenticated:
# Handle view counting
view_exists = db_sess.query(VideoView).filter_by(user_id=current_user.id, video_id=video_id).first()
if not view_exists:
current_video.views += 1
new_view = VideoView(user_id=current_user.id, video_id=video_id)
db_sess.add(new_view)
db_sess.commit()
# Handle likes and subscriptions
likes = json.loads(current_user.likes)
subscriptions = json.loads(current_user.subscriptions)
like = video_id in likes
subscription = current_video.author in subscriptions
This consolidation reduces code duplication and makes the logic clearer.
8. Improving URL Construction for Video Sources and Avatars
Issue:
Constructing URLs for video sources and avatars assumes a specific file naming convention, which might lead to errors if files are missing or named differently.
Solution:
Ensure that files are stored with predictable naming conventions or include file extension data in the database. Additionally, handle cases where files might not exist.
python
import os
from flask import abort
# For video_src
video_path = f'static/vid/{video_id}.mp4'
if not os.path.exists(os.path.join(app.root_path, video_path)):
abort(404)
video_src = url_for("static", filename=f'vid/{video_id}.mp4')
# For avatar_url
avatar_path = f'avatars/{author.avatar}'
if not os.path.exists(os.path.join(app.root_path, 'static', avatar_path)):
avatar_url = url_for('static', filename='avatars/default.png') # Fallback avatar
else:
avatar_url = url_for('static', filename=avatar_path)
9. Security Considerations
Sanitize User Inputs:
Ensure that all user inputs, especially those that will be rendered in templates (like comments), are properly sanitized to prevent XSS attacks. Flask's Jinja2 templates auto-escape variables by default, but it's good to be mindful.
Restrict File Access:
Ensure that users cannot access unauthorized files via the video_src and avatar_url mechanisms. Validate inputs and restrict file serving appropriately.
10. Code Refactoring for Maintainability
Issue:
The video route function is lengthy and handles multiple responsibilities, making it harder to maintain.
Solution:
Break down the function into smaller, reusable components or utility functions. For example:
Refactoring improves readability and makes unit testing individual components easier.
11. Additional Best Practices
Use Pagination for Comments:
For videos with a large number of comments, implement pagination or lazy loading to enhance performance.
Cache Frequently Accessed Data:
Utilize caching mechanisms (like Redis or Flask-Caching) for data that doesn't change frequently, such as last_videos.
Logging:
Implement logging to track significant events, errors, and user actions. This aids in debugging and monitoring.
Error Handling:
Use try-except blocks where appropriate to handle potential exceptions, especially during database operations.
Revised Code Example
Below is a refactored version of your video route incorporating some of the suggestions:
python
from flask import render_template, redirect, url_for, flash, abort
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import joinedload
@app.route('/video/<int:video_id>', methods=['GET', 'POST'])
def video(video_id):
current_video = db_sess.query(Video).get(video_id)
if current_video is None:
return page_not_found('')
comments_enabled = current_video.comments_enabled
author = current_video.author
# Efficiently get the last 10 videos
last_videos = db_sess.query(Video).order_by(Video.datetime.desc()).limit(10).all()
like = False
subscription = False
if current_user.is_authenticated:
# Handle view counting
try:
new_view = VideoView(user_id=current_user.id, video_id=video_id)
db_sess.add(new_view)
current_video.views += 1
db_sess.commit()
except IntegrityError:
db_sess.rollback() # View already exists
# Handle likes and subscriptions using association tables
like = db_sess.query(user_likes).filter_by(user_id=current_user.id, video_id=video_id).first() is not None
subscription = db_sess.query(user_subscriptions).filter_by(user_id=current_user.id, author_id=author.id).first() is not None
# Handle comment form
form = CommentForm()
if comments_enabled and form.validate_on_submit():
if current_user.is_authenticated and not current_user.is_blocked:
handle_comment_submission(db_sess, form, current_user, video_id)
flash('Комментарий добавлен!', 'success')
return redirect(url_for('video', video_id=video_id))
else:
flash('Вы не можете оставить комментарий.', 'danger')
return redirect(url_for('video', video_id=video_id))
# Retrieve comments with eager loading
comments = db_sess.query(Comment).filter(Comment.video_id == video_id).options(
joinedload(Comment.user),
joinedload(Comment.parent).joinedload(Comment.user),
joinedload(Comment.replies).joinedload(Comment.user)
).order_by(Comment.datetime.desc()).all()
# Build root comments
root_comments = [comment for comment in comments if comment.parent_id is None]
# Construct parameters for the template
params = {
'title': f"{current_video.title} - {author.name} {author.surname}",
'current_video': current_video,
'video_src': url_for("static", filename=f'vid/{video_id}.mp4'),
'author': author,
'like': like,
'subscription': subscription,
'comments': root_comments,
'last_videos': last_videos,
'form': form,
'avatar_url': url_for('static', filename=f'avatars/{author.avatar}'),
'authenticated': current_user.is_authenticated,
'current_user': current_user,
}
return render_template('video.html', **params)
This revised version addresses several of the issues discussed, such as removing redundant queries, handling redirects properly, and optimizing the retrieval of the last 10 videos.
Conclusion
Your current implementation effectively covers the necessary functionalities for a video platform. By addressing the highlighted issues and incorporating best practices, you can enhance the performance, maintainability, and security of your application. Always consider scalability and user experience as your platform grows.
If you have specific questions or encounter particular issues with this code, feel free to ask for more targeted assistance!